Merge branch 'unstable'
authorAntonio Ospite <ospite@studenti.unina.it>
Mon, 26 Mar 2012 11:49:31 +0000 (13:49 +0200)
committerAntonio Ospite <ospite@studenti.unina.it>
Mon, 26 Mar 2012 11:49:31 +0000 (13:49 +0200)
24 files changed:
CMakeLists.txt
HACKING.asciidoc
README.asciidoc
TODO
cmake_modules/FindAsciidoc.cmake [new file with mode: 0644]
cmake_modules/FindFFmpeg.cmake [new file with mode: 0644]
cmake_modules/FindXCB.cmake [new file with mode: 0644]
cmake_modules/Findlibusb-1.0.cmake
cmake_modules/MaintenanceTools.cmake [new file with mode: 0644]
contrib/55-am7xxx.rules
doc/CMakeLists.txt [new file with mode: 0644]
doc/Doxyfile.in [new file with mode: 0644]
doc/DoxygenMainpage.dox [new file with mode: 0644]
doc/man/CMakeLists.txt [new file with mode: 0644]
doc/man/am7xxx-play.1.txt [new file with mode: 0644]
doc/man/picoproj.1.txt [new file with mode: 0644]
examples/CMakeLists.txt [new file with mode: 0644]
examples/am7xxx-play.c [new file with mode: 0644]
examples/picoproj.c [new file with mode: 0644]
src/CMakeLists.txt
src/am7xxx.c
src/am7xxx.h
src/libam7xxx.pc.in
src/picoproj.c [deleted file]

index be8e4e7..41cb527 100644 (file)
@@ -16,6 +16,10 @@ set(PROJECT_APIVER
 set(CMAKE_MODULE_PATH 
   ${CMAKE_MODULE_PATH} "${CMAKE_CURRENT_SOURCE_DIR}/cmake_modules/")
 
+OPTION(STRICT_COMPILATION_CHECKS "Enable stricter compilation checks" OFF)
+
+include (MaintenanceTools)
+
 set(EXECUTABLE_OUTPUT_PATH ${CMAKE_BINARY_DIR}/bin)
 set(LIBRARY_OUTPUT_PATH ${CMAKE_BINARY_DIR}/lib)
 set(DOC_OUTPUT_PATH ${CMAKE_BINARY_DIR}/doc)
@@ -32,16 +36,9 @@ if (CMAKE_COMPILER_IS_GNUCC)
 
   # let CFLAGS env override this
   if(CMAKE_C_FLAGS STREQUAL "")
-    set(CMAKE_C_FLAGS "-std=c99 -pedantic -Wall -Wextra -O2")
+    set(CMAKE_C_FLAGS "-std=c99 -pedantic -Wall -Wextra")
   endif()
 
-  # Don't make pedantic checks errors,
-  # as vanilla libusb-1.0.8 can't live with that
-  #add_flags(CMAKE_C_FLAGS -pedantic-errors)
-
-  # GCC >= 4.6
-  #add_flags(CMAKE_C_FLAGS -Wunused-but-set-variable)
-
   add_flags(CMAKE_C_FLAGS
     -fno-common
     -Wall
@@ -68,36 +65,24 @@ if (CMAKE_COMPILER_IS_GNUCC)
     -Wunreachable-code
     -Wunsafe-loop-optimizations
     -Wwrite-strings
-    )
+    -fstack-protector
+    --param=ssp-buffer-size=4)
+
+  if (STRICT_COMPILATION_CHECKS)
+    add_flags(CMAKE_C_FLAGS
+      -Werror
+      # NOTE: Vanilla libusb-1.0.8 can't live with -pedantic-errors
+      -pedantic-errors
+      # NOTE: GCC >= 4.6 is needed for -Wunused-but-set-variable
+      -Wunused-but-set-variable)
+  endif()
 endif()
 
-set(CMAKE_C_FLAGS_DEBUG "-g -DDEBUG=1 -Werror")
+set(CMAKE_C_FLAGS_DEBUG "-O0 -ggdb -DDEBUG=1")
 set(CMAKE_C_FLAGS_RELEASE "-O2")
 set(CMAKE_C_FLAGS_RELWITHDEBINFO "-O2 -g")
 
-# Use git for some maintainance tasks
-find_package(Git)
-if(GIT_FOUND)
-  set(ARCHIVE_PREFIX ${CMAKE_PROJECT_NAME}-${PROJECT_VER})
-  find_program(DATE_EXECUTABLE date DOC "date command line program")
-  if (DATE_EXECUTABLE)
-    message(STATUS "Found date: " ${DATE_EXECUTABLE})
-    message(STATUS "Generator is: " ${CMAKE_GENERATOR})
-
-    # XXX: using $(shell CMD) works only with Unix Makefile
-    if (CMAKE_GENERATOR STREQUAL "Unix Makefiles")
-      message(STATUS " - \"git archive\" will use the date too!")
-      set(ARCHIVE_PREFIX ${ARCHIVE_PREFIX}-$\(shell ${DATE_EXECUTABLE} +%Y%m%d%H%M\))
-    endif()
-  endif()
-  add_custom_target(archive
-    COMMAND ${GIT_EXECUTABLE} archive -o \"${ARCHIVE_PREFIX}.tar.gz\" --prefix=\"${ARCHIVE_PREFIX}/\" HEAD
-    WORKING_DIRECTORY ${CMAKE_SOURCE_DIR})
-
-  add_custom_target(changelog
-    COMMAND ${GIT_EXECUTABLE} log --pretty=\"format:%ai  %aN  <%aE>%n%n%x09* %s%d%n\" > ChangeLog
-    WORKING_DIRECTORY ${CMAKE_SOURCE_DIR})
-endif(GIT_FOUND)
-
 # Add library project
 add_subdirectory(src)
+add_subdirectory(examples)
+add_subdirectory(doc)
index 5b2937d..99dc15e 100644 (file)
@@ -11,7 +11,7 @@ The suggested way to hack on the project is:
 
   $ mkdir build
   $ cd build
-  $ cmake ../ -DCMAKE_BUILD_TYPE=debug
+  $ cmake ../ -DCMAKE_BUILD_TYPE=debug -DSTRICT_COMPILATION_CHECKS=ON
   $ make
 
 If you want to check the code with the ''sparse'' static analysis tool you
@@ -22,3 +22,10 @@ can run:
   $ cmake ../ -DCMAKE_C_COMPILER=cgcc
   $ make
 
+=== Valgrind
+
+You can run the test program under the http://valgrind.org/[valgrind]
+dynamic analyzer by using a command like:
+
+  $ valgrind --leak-check=full --show-reachable=yes --track-origins=yes \
+    ./bin/picoproj -W 800 -H 480 -f my_image.jpg
index 0d878bc..133c13b 100644 (file)
@@ -46,7 +46,7 @@ manually with the command:
 
 Examples of devices based on AM7XXX are:
 
-  - Acer Series C pico projectors (C20 C110 C112):
+  - Acer Series C pico projectors (C20, C110, C112):
       * http://www.acer.it/ac/it/IT/content/models/projector-c
       * http://support.acer.com/product/default.aspx?modelId=3888
     
diff --git a/TODO b/TODO
index ede4343..ebd4ab4 100644 (file)
--- a/TODO
+++ b/TODO
@@ -1,3 +1,2 @@
-- Document the API with Doxygen.
-- Support more than one am7xxx device at a time.
 - Generate language bindings in order to use libam7xxx from other languages.
+- Handle signals in picoproj and do the proper cleanup
diff --git a/cmake_modules/FindAsciidoc.cmake b/cmake_modules/FindAsciidoc.cmake
new file mode 100644 (file)
index 0000000..9b3e414
--- /dev/null
@@ -0,0 +1,27 @@
+# - Find Asciidoc
+# this module looks for asciidoc
+#
+# ASCIIDOC_EXECUTABLE - the full path to asciidoc
+# ASCIIDOC_A2X_EXECUTABLE - the full path to asciidoc's a2x
+# ASCIIDOC_FOUND - If false, don't attempt to use asciidoc.
+#
+# Taken from:
+# http://lissyx.dyndns.org/redmine/projects/qpdfpresenterconsole/repository/revisions/master/raw/cmake/FindAsciidoc.cmake
+
+FIND_PROGRAM(ASCIIDOC_EXECUTABLE asciidoc)
+FIND_PROGRAM(ASCIIDOC_A2X_EXECUTABLE a2x)
+
+MARK_AS_ADVANCED(
+ASCIIDOC_EXECUTABLE
+ASCIIDOC_A2X_EXECUTABLE
+)
+
+IF ((NOT ASCIIDOC_EXECUTABLE) OR (NOT ASCIIDOC_A2X_EXECUTABLE))
+SET(ASCIIDOC_FOUND "NO")
+ELSE ((NOT ASCIIDOC_EXECUTABLE) OR (NOT ASCIIDOC_A2X_EXECUTABLE))
+SET(ASCIIDOC_FOUND "YES")
+ENDIF ((NOT ASCIIDOC_EXECUTABLE) OR (NOT ASCIIDOC_A2X_EXECUTABLE))
+
+IF (NOT ASCIIDOC_FOUND AND Asciidoc_FIND_REQUIRED)
+MESSAGE(FATAL_ERROR "Could not find asciidoc")
+ENDIF (NOT ASCIIDOC_FOUND AND Asciidoc_FIND_REQUIRED)
diff --git a/cmake_modules/FindFFmpeg.cmake b/cmake_modules/FindFFmpeg.cmake
new file mode 100644 (file)
index 0000000..eabe5a0
--- /dev/null
@@ -0,0 +1,126 @@
+# Locate ffmpeg
+# This module defines
+# FFMPEG_LIBRARIES
+# FFMPEG_FOUND, if false, do not try to link to ffmpeg
+# FFMPEG_INCLUDE_DIR, where to find the headers
+#
+# $FFMPEG_DIR is an environment variable that would
+# correspond to the ./configure --prefix=$FFMPEG_DIR
+#
+# Created by Robert Osfield.
+
+
+#In ffmpeg code, old version use "#include <header.h>" and newer use "#include <libname/header.h>"
+#In OSG ffmpeg plugin, we use "#include <header.h>" for compatibility with old version of ffmpeg
+
+#We have to search the path which contain the header.h (usefull for old version)
+#and search the path which contain the libname/header.h (usefull for new version)
+
+#Then we need to include ${FFMPEG_libname_INCLUDE_DIRS} (in old version case, use by ffmpeg header and osg plugin code)
+#                                                       (in new version case, use by ffmpeg header) 
+#and ${FFMPEG_libname_INCLUDE_DIRS/libname}             (in new version case, use by osg plugin code)
+
+
+# Macro to find header and lib directories
+# example: FFMPEG_FIND(AVFORMAT avformat avformat.h)
+MACRO(FFMPEG_FIND varname shortname headername)
+    # old version of ffmpeg put header in $prefix/include/[ffmpeg]
+    # so try to find header in include directory
+    FIND_PATH(FFMPEG_${varname}_INCLUDE_DIRS ${headername}
+        PATHS
+        ${FFMPEG_ROOT}/include
+        $ENV{FFMPEG_DIR}/include
+        $ENV{OSGDIR}/include
+        $ENV{OSG_ROOT}/include
+        ~/Library/Frameworks
+        /Library/Frameworks
+        /usr/local/include
+        /usr/include
+        /sw/include # Fink
+        /opt/local/include # DarwinPorts
+        /opt/csw/include # Blastwave
+        /opt/include
+        /usr/freeware/include
+        PATH_SUFFIXES ffmpeg
+        DOC "Location of FFMPEG Headers"
+    )
+
+    # newer version of ffmpeg put header in $prefix/include/[ffmpeg/]lib${shortname}
+    # so try to find lib${shortname}/header in include directory
+    IF(NOT FFMPEG_${varname}_INCLUDE_DIRS)
+        FIND_PATH(FFMPEG_${varname}_INCLUDE_DIRS lib${shortname}/${headername}
+            ${FFMPEG_ROOT}/include
+            $ENV{FFMPEG_DIR}/include
+            $ENV{OSGDIR}/include
+            $ENV{OSG_ROOT}/include
+            ~/Library/Frameworks
+            /Library/Frameworks
+            /usr/local/include
+            /usr/include/
+            /sw/include # Fink
+            /opt/local/include # DarwinPorts
+            /opt/csw/include # Blastwave
+            /opt/include
+            /usr/freeware/include
+            PATH_SUFFIXES ffmpeg
+            DOC "Location of FFMPEG Headers"
+        )
+    ENDIF(NOT FFMPEG_${varname}_INCLUDE_DIRS)
+
+    FIND_LIBRARY(FFMPEG_${varname}_LIBRARIES
+        NAMES ${shortname}
+        PATHS
+        ${FFMPEG_ROOT}/lib
+        $ENV{FFMPEG_DIR}/lib
+        $ENV{OSGDIR}/lib
+        $ENV{OSG_ROOT}/lib
+        ~/Library/Frameworks
+        /Library/Frameworks
+        /usr/local/lib
+        /usr/local/lib64
+        /usr/lib
+        /usr/lib64
+        /sw/lib
+        /opt/local/lib
+        /opt/csw/lib
+        /opt/lib
+        /usr/freeware/lib64
+        DOC "Location of FFMPEG Libraries"
+    )
+
+    IF (FFMPEG_${varname}_LIBRARIES AND FFMPEG_${varname}_INCLUDE_DIRS)
+        SET(FFMPEG_${varname}_FOUND 1)
+    ENDIF(FFMPEG_${varname}_LIBRARIES AND FFMPEG_${varname}_INCLUDE_DIRS)
+
+ENDMACRO(FFMPEG_FIND)
+
+SET(FFMPEG_ROOT "$ENV{FFMPEG_DIR}" CACHE PATH "Location of FFMPEG")
+
+FFMPEG_FIND(LIBAVFORMAT avformat avformat.h)
+FFMPEG_FIND(LIBAVDEVICE avdevice avdevice.h)
+FFMPEG_FIND(LIBAVCODEC  avcodec  avcodec.h)
+FFMPEG_FIND(LIBAVUTIL   avutil   avutil.h)
+FFMPEG_FIND(LIBSWSCALE  swscale  swscale.h)  # not sure about the header to look for here.
+
+SET(FFMPEG_FOUND "NO")
+# Note we don't check FFMPEG_LIBSWSCALE_FOUND here, it's optional.
+IF   (FFMPEG_LIBAVFORMAT_FOUND AND FFMPEG_LIBAVDEVICE_FOUND AND FFMPEG_LIBAVCODEC_FOUND AND FFMPEG_LIBAVUTIL_FOUND)
+
+    SET(FFMPEG_FOUND "YES")
+
+    SET(FFMPEG_INCLUDE_DIRS ${FFMPEG_LIBAVFORMAT_INCLUDE_DIRS})
+
+    SET(FFMPEG_LIBRARY_DIRS ${FFMPEG_LIBAVFORMAT_LIBRARY_DIRS})
+
+    # Note we don't add FFMPEG_LIBSWSCALE_LIBRARIES here, it will be added if found later.
+    SET(FFMPEG_LIBRARIES
+        ${FFMPEG_LIBAVFORMAT_LIBRARIES}
+        ${FFMPEG_LIBAVDEVICE_LIBRARIES}
+        ${FFMPEG_LIBAVCODEC_LIBRARIES}
+        ${FFMPEG_LIBAVUTIL_LIBRARIES})
+
+ELSE (FFMPEG_LIBAVFORMAT_FOUND AND FFMPEG_LIBAVDEVICE_FOUND AND FFMPEG_LIBAVCODEC_FOUND AND FFMPEG_LIBAVUTIL_FOUND)
+
+#    MESSAGE(STATUS "Could not find FFMPEG")
+
+ENDIF(FFMPEG_LIBAVFORMAT_FOUND AND FFMPEG_LIBAVDEVICE_FOUND AND FFMPEG_LIBAVCODEC_FOUND AND FFMPEG_LIBAVUTIL_FOUND)
diff --git a/cmake_modules/FindXCB.cmake b/cmake_modules/FindXCB.cmake
new file mode 100644 (file)
index 0000000..517ad26
--- /dev/null
@@ -0,0 +1,43 @@
+# - Try to find libxcb
+# Once done this will define
+#
+#  LIBXCB_FOUND - system has libxcb
+#  LIBXCB_LIBRARIES - Link these to use libxcb
+#  LIBXCB_INCLUDE_DIR - the libxcb include dir
+#  LIBXCB_DEFINITIONS - compiler switches required for using libxcb
+
+# Copyright (c) 2008 Helio Chissini de Castro, <helio@kde.org>
+# Copyright (c) 2007, Matthias Kretz, <kretz@kde.org>
+#
+# Redistribution and use is allowed according to the terms of the BSD license.
+# For details see the accompanying COPYING-CMAKE-SCRIPTS file.
+
+
+IF (NOT WIN32)
+  IF (LIBXCB_INCLUDE_DIR AND LIBXCB_LIBRARIES)
+    # in cache already
+    SET(XCB_FIND_QUIETLY TRUE)
+  ENDIF (LIBXCB_INCLUDE_DIR AND LIBXCB_LIBRARIES)
+
+  # use pkg-config to get the directories and then use these values
+  # in the FIND_PATH() and FIND_LIBRARY() calls
+  FIND_PACKAGE(PkgConfig)
+  PKG_CHECK_MODULES(PKG_XCB xcb)
+
+  SET(LIBXCB_DEFINITIONS ${PKG_XCB_CFLAGS})
+
+  FIND_PATH(LIBXCB_INCLUDE_DIR xcb/xcb.h
+    ${PKG_XCB_INCLUDE_DIRS}
+    )
+
+  FIND_LIBRARY(LIBXCB_LIBRARIES NAMES xcb libxcb
+    PATHS
+    ${PKG_XCB_LIBRARY_DIRS}
+    )
+
+  include(FindPackageHandleStandardArgs)
+  FIND_PACKAGE_HANDLE_STANDARD_ARGS(XCB DEFAULT_MSG LIBXCB_INCLUDE_DIR LIBXCB_LIBRARIES )
+
+
+  MARK_AS_ADVANCED(LIBXCB_INCLUDE_DIR LIBXCB_LIBRARIES XCBPROC_EXECUTABLE)
+ENDIF (NOT WIN32)
index 405ed51..ec40055 100644 (file)
@@ -49,7 +49,7 @@ if (LIBUSB_1_LIBRARIES AND LIBUSB_1_INCLUDE_DIRS)
 else (LIBUSB_1_LIBRARIES AND LIBUSB_1_INCLUDE_DIRS)
   find_path(LIBUSB_1_INCLUDE_DIR
     NAMES
-       libusb-1.0/libusb.h
+       libusb.h
     PATHS
       /usr/include
       /usr/local/include
@@ -61,7 +61,7 @@ else (LIBUSB_1_LIBRARIES AND LIBUSB_1_INCLUDE_DIRS)
 
   find_library(LIBUSB_1_LIBRARY
     NAMES
-      usb-1.0
+      usb-1.0 usb
     PATHS
       /usr/lib
       /usr/local/lib
@@ -95,4 +95,4 @@ else (LIBUSB_1_LIBRARIES AND LIBUSB_1_INCLUDE_DIRS)
   # show the LIBUSB_1_INCLUDE_DIRS and LIBUSB_1_LIBRARIES variables only in the advanced view
   mark_as_advanced(LIBUSB_1_INCLUDE_DIRS LIBUSB_1_LIBRARIES)
 
-endif (LIBUSB_1_LIBRARIES AND LIBUSB_1_INCLUDE_DIRS)
\ No newline at end of file
+endif (LIBUSB_1_LIBRARIES AND LIBUSB_1_INCLUDE_DIRS)
diff --git a/cmake_modules/MaintenanceTools.cmake b/cmake_modules/MaintenanceTools.cmake
new file mode 100644 (file)
index 0000000..4b90336
--- /dev/null
@@ -0,0 +1,27 @@
+# Use git for some maintenance tasks
+find_package(Git)
+if(GIT_FOUND)
+
+  # Add an 'archive' target to generate a compressed archive from the git source code
+  set(ARCHIVE_PREFIX ${CMAKE_PROJECT_NAME}-${PROJECT_VER})
+  find_program(DATE_EXECUTABLE date DOC "date command line program")
+  if (DATE_EXECUTABLE)
+    message(STATUS "Found date: " ${DATE_EXECUTABLE})
+    message(STATUS "Generator is: " ${CMAKE_GENERATOR})
+
+    # XXX: using $(shell CMD) works only with Unix Makefile
+    if (CMAKE_GENERATOR STREQUAL "Unix Makefiles")
+      message(STATUS " - \"git archive\" will use the date too!")
+      set(ARCHIVE_PREFIX ${ARCHIVE_PREFIX}-$\(shell ${DATE_EXECUTABLE} +%Y%m%d%H%M\))
+    endif()
+  endif()
+  add_custom_target(archive
+    COMMAND ${GIT_EXECUTABLE} archive -o \"${CMAKE_BINARY_DIR}/${ARCHIVE_PREFIX}.tar.gz\" --prefix=\"${ARCHIVE_PREFIX}/\" HEAD
+    WORKING_DIRECTORY ${CMAKE_SOURCE_DIR})
+
+  # Add a 'changelog' target to generate a qausi-GNU-style changelog, it may
+  # be used by distributors to ship when building their packages.
+  add_custom_target(changelog
+    COMMAND ${GIT_EXECUTABLE} log --pretty=\"format:%ai  %aN  <%aE>%n%n%x09* %s%d%n\" > \"${CMAKE_BINARY_DIR}/ChangeLog\"
+    WORKING_DIRECTORY ${CMAKE_SOURCE_DIR})
+endif(GIT_FOUND)
index 1c9d02d..1b7d266 100644 (file)
@@ -1,2 +1,4 @@
 # Acer C110
 ACTION=="add", SUBSYSTEM=="usb", ATTRS{idVendor}=="1de1", ATTRS{idProduct}=="c101", MODE="0660", GROUP="plugdev"
+# Philips/Sagemcom PicoPix 1020
+ACTION=="add", SUBSYSTEM=="usb", ATTRS{idVendor}=="21e7", ATTRS{idProduct}=="000e", MODE="0660", GROUP="plugdev"
diff --git a/doc/CMakeLists.txt b/doc/CMakeLists.txt
new file mode 100644 (file)
index 0000000..0569f9d
--- /dev/null
@@ -0,0 +1,17 @@
+# add a target to generate API documentation with Doxygen
+find_package(Doxygen)
+if(DOXYGEN_FOUND)
+  configure_file("Doxyfile.in" "Doxyfile" @ONLY IMMEDIATE)
+
+  add_custom_target(doc
+    ${DOXYGEN_EXECUTABLE} ${CMAKE_CURRENT_BINARY_DIR}/Doxyfile
+    WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
+    COMMENT "Generating API documentation with Doxygen" VERBATIM
+  )
+
+  install(DIRECTORY ${DOC_OUTPUT_PATH}/html
+    DESTINATION "${CMAKE_INSTALL_PREFIX}/share/doc/${CMAKE_PROJECT_NAME}")
+
+endif(DOXYGEN_FOUND)
+
+add_subdirectory(man)
diff --git a/doc/Doxyfile.in b/doc/Doxyfile.in
new file mode 100644 (file)
index 0000000..4e6a877
--- /dev/null
@@ -0,0 +1,291 @@
+# Doxyfile 1.7.6.1
+
+#---------------------------------------------------------------------------
+# Project related configuration options
+#---------------------------------------------------------------------------
+DOXYFILE_ENCODING      = UTF-8
+PROJECT_NAME           = @PROJECT_NAME@
+PROJECT_NUMBER         = @PROJECT_APIVER@
+PROJECT_BRIEF          = "@PROJECT_DESCRIPTION@"
+PROJECT_LOGO           =
+OUTPUT_DIRECTORY       = @DOC_OUTPUT_PATH@
+CREATE_SUBDIRS         = NO
+OUTPUT_LANGUAGE        = English
+BRIEF_MEMBER_DESC      = YES
+REPEAT_BRIEF           = YES
+ABBREVIATE_BRIEF       =
+ALWAYS_DETAILED_SEC    = NO
+INLINE_INHERITED_MEMB  = NO
+FULL_PATH_NAMES        = YES
+STRIP_FROM_PATH        = @CMAKE_SOURCE_DIR@
+STRIP_FROM_INC_PATH    =
+SHORT_NAMES            = NO
+JAVADOC_AUTOBRIEF      = YES
+QT_AUTOBRIEF           = NO
+MULTILINE_CPP_IS_BRIEF = NO
+INHERIT_DOCS           = YES
+SEPARATE_MEMBER_PAGES  = NO
+TAB_SIZE               = 8
+ALIASES                =
+TCL_SUBST              =
+OPTIMIZE_OUTPUT_FOR_C  = YES
+OPTIMIZE_OUTPUT_JAVA   = NO
+OPTIMIZE_FOR_FORTRAN   = NO
+OPTIMIZE_OUTPUT_VHDL   = NO
+EXTENSION_MAPPING      =
+BUILTIN_STL_SUPPORT    = NO
+CPP_CLI_SUPPORT        = NO
+SIP_SUPPORT            = NO
+IDL_PROPERTY_SUPPORT   = YES
+DISTRIBUTE_GROUP_DOC   = NO
+SUBGROUPING            = YES
+INLINE_GROUPED_CLASSES = NO
+INLINE_SIMPLE_STRUCTS  = NO
+TYPEDEF_HIDES_STRUCT   = NO
+SYMBOL_CACHE_SIZE      = 0
+LOOKUP_CACHE_SIZE      = 0
+#---------------------------------------------------------------------------
+# Build related configuration options
+#---------------------------------------------------------------------------
+EXTRACT_ALL            = NO
+EXTRACT_PRIVATE        = NO
+EXTRACT_STATIC         = NO
+EXTRACT_LOCAL_CLASSES  = NO
+EXTRACT_LOCAL_METHODS  = NO
+EXTRACT_ANON_NSPACES   = NO
+HIDE_UNDOC_MEMBERS     = NO
+HIDE_UNDOC_CLASSES     = NO
+HIDE_FRIEND_COMPOUNDS  = NO
+HIDE_IN_BODY_DOCS      = NO
+INTERNAL_DOCS          = NO
+CASE_SENSE_NAMES       = YES
+HIDE_SCOPE_NAMES       = NO
+SHOW_INCLUDE_FILES     = YES
+FORCE_LOCAL_INCLUDES   = NO
+INLINE_INFO            = YES
+SORT_MEMBER_DOCS       = YES
+SORT_BRIEF_DOCS        = NO
+SORT_MEMBERS_CTORS_1ST = NO
+SORT_GROUP_NAMES       = NO
+SORT_BY_SCOPE_NAME     = NO
+STRICT_PROTO_MATCHING  = NO
+GENERATE_TODOLIST      = YES
+GENERATE_TESTLIST      = YES
+GENERATE_BUGLIST       = YES
+GENERATE_DEPRECATEDLIST= YES
+ENABLED_SECTIONS       =
+MAX_INITIALIZER_LINES  = 30
+SHOW_USED_FILES        = YES
+SHOW_DIRECTORIES       = NO
+SHOW_FILES             = YES
+SHOW_NAMESPACES        = YES
+FILE_VERSION_FILTER    =
+LAYOUT_FILE            =
+CITE_BIB_FILES         =
+#---------------------------------------------------------------------------
+# configuration options related to warning and progress messages
+#---------------------------------------------------------------------------
+QUIET                  = NO
+WARNINGS               = YES
+WARN_IF_UNDOCUMENTED   = YES
+WARN_IF_DOC_ERROR      = YES
+WARN_NO_PARAMDOC       = NO
+WARN_FORMAT            = "$file:$line: $text"
+WARN_LOGFILE           =
+#---------------------------------------------------------------------------
+# configuration options related to the input files
+#---------------------------------------------------------------------------
+INPUT                  = @CMAKE_CURRENT_SOURCE_DIR@/ \
+                         @CMAKE_SOURCE_DIR@/src/ \
+                         @CMAKE_SOURCE_DIR@/examples/
+INPUT_ENCODING         = UTF-8
+FILE_PATTERNS          = *.dox \
+                         *.h \
+                         *.c
+RECURSIVE              = NO
+EXCLUDE                =
+EXCLUDE_SYMLINKS       = NO
+EXCLUDE_PATTERNS       =
+EXCLUDE_SYMBOLS        =
+EXAMPLE_PATH           = @CMAKE_SOURCE_DIR@/examples/
+EXAMPLE_PATTERNS       = *.c
+EXAMPLE_RECURSIVE      = NO
+IMAGE_PATH             =
+INPUT_FILTER           =
+FILTER_PATTERNS        =
+FILTER_SOURCE_FILES    = NO
+FILTER_SOURCE_PATTERNS =
+#---------------------------------------------------------------------------
+# configuration options related to source browsing
+#---------------------------------------------------------------------------
+SOURCE_BROWSER         = YES
+INLINE_SOURCES         = YES
+STRIP_CODE_COMMENTS    = YES
+REFERENCED_BY_RELATION = NO
+REFERENCES_RELATION    = NO
+REFERENCES_LINK_SOURCE = YES
+USE_HTAGS              = NO
+VERBATIM_HEADERS       = YES
+#---------------------------------------------------------------------------
+# configuration options related to the alphabetical class index
+#---------------------------------------------------------------------------
+ALPHABETICAL_INDEX     = YES
+COLS_IN_ALPHA_INDEX    = 5
+IGNORE_PREFIX          =
+#---------------------------------------------------------------------------
+# configuration options related to the HTML output
+#---------------------------------------------------------------------------
+GENERATE_HTML          = YES
+HTML_OUTPUT            = html
+HTML_FILE_EXTENSION    = .html
+HTML_HEADER            =
+HTML_FOOTER            =
+HTML_STYLESHEET        =
+HTML_EXTRA_FILES       =
+HTML_COLORSTYLE_HUE    = 220
+HTML_COLORSTYLE_SAT    = 100
+HTML_COLORSTYLE_GAMMA  = 80
+HTML_TIMESTAMP         = YES
+HTML_ALIGN_MEMBERS     = YES
+HTML_DYNAMIC_SECTIONS  = NO
+GENERATE_DOCSET        = NO
+DOCSET_FEEDNAME        = "Doxygen generated docs"
+DOCSET_BUNDLE_ID       = org.doxygen.Project
+DOCSET_PUBLISHER_ID    = org.doxygen.Publisher
+DOCSET_PUBLISHER_NAME  = Publisher
+GENERATE_HTMLHELP      = NO
+CHM_FILE               =
+HHC_LOCATION           =
+GENERATE_CHI           = NO
+CHM_INDEX_ENCODING     =
+BINARY_TOC             = NO
+TOC_EXPAND             = NO
+GENERATE_QHP           = NO
+QCH_FILE               =
+QHP_NAMESPACE          = org.doxygen.Project
+QHP_VIRTUAL_FOLDER     = doc
+QHP_CUST_FILTER_NAME   =
+QHP_CUST_FILTER_ATTRS  =
+QHP_SECT_FILTER_ATTRS  =
+QHG_LOCATION           =
+GENERATE_ECLIPSEHELP   = NO
+ECLIPSE_DOC_ID         = org.doxygen.Project
+DISABLE_INDEX          = NO
+GENERATE_TREEVIEW      = NO
+ENUM_VALUES_PER_LINE   = 4
+USE_INLINE_TREES       = NO
+TREEVIEW_WIDTH         = 250
+EXT_LINKS_IN_WINDOW    = NO
+FORMULA_FONTSIZE       = 10
+FORMULA_TRANSPARENT    = YES
+USE_MATHJAX            = NO
+MATHJAX_RELPATH        = http://www.mathjax.org/mathjax
+MATHJAX_EXTENSIONS     =
+SEARCHENGINE           = YES
+SERVER_BASED_SEARCH    = NO
+#---------------------------------------------------------------------------
+# configuration options related to the LaTeX output
+#---------------------------------------------------------------------------
+GENERATE_LATEX         = NO
+LATEX_OUTPUT           = latex
+LATEX_CMD_NAME         = latex
+MAKEINDEX_CMD_NAME     = makeindex
+COMPACT_LATEX          = NO
+PAPER_TYPE             = a4
+EXTRA_PACKAGES         =
+LATEX_HEADER           =
+LATEX_FOOTER           =
+PDF_HYPERLINKS         = YES
+USE_PDFLATEX           = YES
+LATEX_BATCHMODE        = NO
+LATEX_HIDE_INDICES     = NO
+LATEX_SOURCE_CODE      = NO
+LATEX_BIB_STYLE        = plain
+#---------------------------------------------------------------------------
+# configuration options related to the RTF output
+#---------------------------------------------------------------------------
+GENERATE_RTF           = NO
+RTF_OUTPUT             = rtf
+COMPACT_RTF            = NO
+RTF_HYPERLINKS         = NO
+RTF_STYLESHEET_FILE    =
+RTF_EXTENSIONS_FILE    =
+#---------------------------------------------------------------------------
+# configuration options related to the man page output
+#---------------------------------------------------------------------------
+GENERATE_MAN           = NO
+MAN_OUTPUT             = man
+MAN_EXTENSION          = .3
+MAN_LINKS              = NO
+#---------------------------------------------------------------------------
+# configuration options related to the XML output
+#---------------------------------------------------------------------------
+GENERATE_XML           = NO
+XML_OUTPUT             = xml
+XML_SCHEMA             =
+XML_DTD                =
+XML_PROGRAMLISTING     = YES
+#---------------------------------------------------------------------------
+# configuration options for the AutoGen Definitions output
+#---------------------------------------------------------------------------
+GENERATE_AUTOGEN_DEF   = NO
+#---------------------------------------------------------------------------
+# configuration options related to the Perl module output
+#---------------------------------------------------------------------------
+GENERATE_PERLMOD       = NO
+PERLMOD_LATEX          = NO
+PERLMOD_PRETTY         = YES
+PERLMOD_MAKEVAR_PREFIX =
+#---------------------------------------------------------------------------
+# Configuration options related to the preprocessor
+#---------------------------------------------------------------------------
+ENABLE_PREPROCESSING   = YES
+MACRO_EXPANSION        = NO
+EXPAND_ONLY_PREDEF     = NO
+SEARCH_INCLUDES        = YES
+INCLUDE_PATH           =
+INCLUDE_FILE_PATTERNS  =
+PREDEFINED             =
+EXPAND_AS_DEFINED      =
+SKIP_FUNCTION_MACROS   = YES
+#---------------------------------------------------------------------------
+# Configuration::additions related to external references
+#---------------------------------------------------------------------------
+TAGFILES               =
+GENERATE_TAGFILE       =
+ALLEXTERNALS           = NO
+EXTERNAL_GROUPS        = YES
+PERL_PATH              = /usr/bin/perl
+#---------------------------------------------------------------------------
+# Configuration options related to the dot tool
+#---------------------------------------------------------------------------
+CLASS_DIAGRAMS         = NO
+MSCGEN_PATH            =
+HIDE_UNDOC_RELATIONS   = YES
+HAVE_DOT               = NO
+DOT_NUM_THREADS        = 0
+DOT_FONTNAME           = Helvetica
+DOT_FONTSIZE           = 10
+DOT_FONTPATH           =
+CLASS_GRAPH            = YES
+COLLABORATION_GRAPH    = YES
+GROUP_GRAPHS           = YES
+UML_LOOK               = NO
+TEMPLATE_RELATIONS     = NO
+INCLUDE_GRAPH          = YES
+INCLUDED_BY_GRAPH      = YES
+CALL_GRAPH             = NO
+CALLER_GRAPH           = NO
+GRAPHICAL_HIERARCHY    = YES
+DIRECTORY_GRAPH        = YES
+DOT_IMAGE_FORMAT       = png
+INTERACTIVE_SVG        = NO
+DOT_PATH               =
+DOTFILE_DIRS           =
+MSCFILE_DIRS           =
+DOT_GRAPH_MAX_NODES    = 50
+MAX_DOT_GRAPH_DEPTH    = 0
+DOT_TRANSPARENT        = NO
+DOT_MULTI_TARGETS      = YES
+GENERATE_LEGEND        = YES
+DOT_CLEANUP            = YES
diff --git a/doc/DoxygenMainpage.dox b/doc/DoxygenMainpage.dox
new file mode 100644 (file)
index 0000000..2453dc2
--- /dev/null
@@ -0,0 +1,42 @@
+/**
+@mainpage  libam7xxx
+
+@author Antonio Ospite <ospite@studenti.unina.it>
+@copyright GNU General Public License version 2.
+
+Website: http://git.ao2.it/libam7xxx.git
+
+@section libam7xxxIntro Introduction
+
+libam7xxx is an Open Source library to communicate via USB with projectors and
+Digital Picture Frames based on the Actions Micro AM7XXX family if ICs.
+
+libam7xxx makes it possible to use these devices as USB displays on
+non-Windows Operating Systems like GNU/Linux or Android/Linux just to name
+a few, and on non-PC platforms like for instance mobile phones, tablets or
+game consoles.
+
+Check @link am7xxx.h @endlink for the public API documentation.
+
+@section libam7xxxSupportedDevices Supported Devices
+
+- Acer C110
+- Philips/SagemCom PicoPix 1020
+
+@section libam7xxxDesignOverview Design Overview
+
+libam7xxx provides access to devices via two structs:
+
+- A context, which manages aspects of thread safety when using
+  multiple devices on multiple threads.
+- A device, which talks to the hardware and manages transfers and configuration.
+
+Either or both of these structs are passed to the functions in order
+to interact with the hardware. The USB access is handled by
+libusb-1.0, which should work in a mostly non-blocking fashion across
+all platforms (see function documentation for specifics).
+
+The API and the project structure has been inspired by
+<a href="http://openkinect.org">libfreenect</a>.
+
+*/
diff --git a/doc/man/CMakeLists.txt b/doc/man/CMakeLists.txt
new file mode 100644 (file)
index 0000000..8029513
--- /dev/null
@@ -0,0 +1,16 @@
+# add a target to generate man pages with asciidoc
+find_package(Asciidoc)
+if(ASCIIDOC_FOUND)
+  add_custom_target(manpages
+    ${ASCIIDOC_A2X_EXECUTABLE} -f manpage ${CMAKE_CURRENT_SOURCE_DIR}/am7xxx-play.1.txt -D ${CMAKE_CURRENT_BINARY_DIR}
+    COMMAND ${ASCIIDOC_A2X_EXECUTABLE} -f manpage ${CMAKE_CURRENT_SOURCE_DIR}/picoproj.1.txt -D ${CMAKE_CURRENT_BINARY_DIR}
+    WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
+    COMMENT "Generating man pages with Asciidoc" VERBATIM
+  )
+
+install(FILES
+  ${DOC_OUTPUT_PATH}/man/am7xxx-play.1
+  ${DOC_OUTPUT_PATH}/man/picoproj.1
+  DESTINATION "${CMAKE_INSTALL_PREFIX}/share/man/man1/")
+
+endif(ASCIIDOC_FOUND)
diff --git a/doc/man/am7xxx-play.1.txt b/doc/man/am7xxx-play.1.txt
new file mode 100644 (file)
index 0000000..5054da4
--- /dev/null
@@ -0,0 +1,100 @@
+AM7XXX-PLAY(1)
+==============
+:doctype: manpage
+
+
+NAME
+----
+am7xxx-play - play stuff on an am7xxx device (e.g. Acer C110, PicoPix 1020)
+
+
+SYNOPSIS
+--------
+*am7xxx-play* ['OPTIONS']
+
+
+DESCRIPTION
+-----------
+am7xxx-play(1) uses libavdevice, libavformat, libavcodec and libswscale to
+decode the input, encode it to jpeg and display it with libam7xxx.
+
+
+OPTIONS
+-------
+*-f* '<input format>'::
+    the input device format
+
+*-i* '<input path>'::
+    the input path
+
+*-o* '<options>'::
+    a comma separated list of input format options
++
+EXAMPLE:
++
+  -o draw_mouse=1,framerate=100,video_size=800x480
+
+*-s* '<scaling method>'::
+    the rescaling method (see swscale.h)
+
+*-u*::
+    upscale the image if smaller than the display dimensions
+
+*-F* '<format>'::
+    the image format to use (default is JPEG)
++
+.SUPPORTED FORMATS:
+* 1 - JPEG
+* 2 - NV12
+
+*-q* '<quality>'::
+    quality of jpeg sent to the device, between 1 and 100
+
+*-l* '<log level>'::
+    the verbosity level of libam7xxx output (0-5)
+
+*-p* '<power level>'::
+    power level of device, between 0 (off) and 4 (maximum) +
+    WARNING: Level 2 and greater require the master AND
+             the slave connector to be plugged in.
+
+*-h*::
+    this help message
+
+
+EXAMPLES OF USE
+---------------
+
+   am7xxx-play -f x11grab -i :0.0 -o video_size=800x480
+   am7xxx-play -f fbdev -i /dev/fb0
+   am7xxx-play -f video4linux2 -i /dev/video0 -o video_size=320x240,frame_rate=100 -u -q 90
+   am7xxx-play -i http://download.blender.org/peach/bigbuckbunny_movies/BigBuckBunny_640x360.m4v
+
+
+EXIT STATUS
+-----------
+*0*::
+    Success
+
+*!0*::
+    Failure (libam7xxx error; libav error)
+
+
+AUTHORS
+-------
+Antonio Ospite and Reto Schneider
+
+
+RESOURCES
+---------
+Main web site: <http://git.ao2.it/libam7xxx.git>
+
+
+COPYING
+-------
+Copyright \(C) 2012  Antonio Ospite <ospite@studenti.unina.it>
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
diff --git a/doc/man/picoproj.1.txt b/doc/man/picoproj.1.txt
new file mode 100644 (file)
index 0000000..e26df26
--- /dev/null
@@ -0,0 +1,80 @@
+PICOPROJ(1)
+===========
+:doctype: manpage
+
+
+NAME
+----
+picoproj - test program for libam7xxx
+
+
+SYNOPSIS
+--------
+*picoproj* ['OPTIONS']
+
+
+DESCRIPTION
+-----------
+picoproj(1) is a minimal example to show how to use libam7xxx to display a static image.
+
+
+OPTIONS
+-------
+
+*-f* '<filename>'::
+    the image file to upload
+
+
+*-F* '<format>'::
+    the image format to use (default is JPEG)
++
+.SUPPORTED FORMATS:
+* 1 - JPEG
+* 2 - NV12
+
+*-l* '<log level>'::
+    the verbosity level of libam7xxx output (0-5)
+
+*-W* '<image width>'::
+    the width of the image to upload
+
+*-H* '<image height>'::
+    the height of the image to upload
+
+*-h*::
+    this help message
+
+
+EXAMPLE OF USE
+--------------
+
+picoproj -f file.jpg -F 1 -l 5 -W 800 -H 480
+
+
+EXIT STATUS
+-----------
+*0*::
+    Success
+
+*!0*::
+    Failure (libam7xxx error)
+
+
+AUTHORS
+-------
+Antonio Ospite and Reto Schneider
+
+
+RESOURCES
+---------
+Main web site: <http://git.ao2.it/libam7xxx.git>
+
+
+COPYING
+-------
+Copyright \(C) 2012  Antonio Ospite <ospite@studenti.unina.it>
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt
new file mode 100644 (file)
index 0000000..234e666
--- /dev/null
@@ -0,0 +1,35 @@
+add_definitions("-D_POSIX_C_SOURCE=2") # for getopt()
+add_definitions("-D_POSIX_SOURCE") # for sigaction
+add_definitions("-D_BSD_SOURCE") # for strdup
+
+include_directories(${CMAKE_SOURCE_DIR}/src/)
+
+# Build a test app that sends a single picture
+add_executable(picoproj picoproj.c)
+target_link_libraries(picoproj am7xxx)
+install(TARGETS picoproj
+  DESTINATION "${CMAKE_INSTALL_PREFIX}/bin")
+
+# Build a more complete example
+find_package(FFmpeg REQUIRED)
+
+include_directories(${FFMPEG_LIBAVDEVICE_INCLUDE_DIRS})
+include_directories(${FFMPEG_LIBAVFORMAT_INCLUDE_DIRS})
+include_directories(${FFMPEG_LIBSWSCALE_INCLUDE_DIRS})
+
+# xcb is used to retrieve the full screen dimensions when using x11grab
+# as input format
+find_package(XCB)
+if (XCB_FOUND)
+  add_definitions("${LIBXCB_DEFINITIONS} -DHAVE_XCB")
+  include_directories(${LIBXCB_INCLUDE_DIRS})
+endif()
+
+add_executable(am7xxx-play am7xxx-play.c)
+
+target_link_libraries(am7xxx-play am7xxx
+  ${FFMPEG_LIBRARIES}
+  ${FFMPEG_LIBSWSCALE_LIBRARIES}
+  ${LIBXCB_LIBRARIES})
+install(TARGETS am7xxx-play
+  DESTINATION "${CMAKE_INSTALL_PREFIX}/bin")
diff --git a/examples/am7xxx-play.c b/examples/am7xxx-play.c
new file mode 100644 (file)
index 0000000..54f92e9
--- /dev/null
@@ -0,0 +1,788 @@
+/*
+ * am7xxx-play - play stuff on an am7xxx device (e.g. Acer C110, PicoPix 1020)
+ *
+ * Copyright (C) 2012  Antonio Ospite <ospite@studenti.unina.it>
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+/**
+ * @example examples/am7xxx-play.c
+ * am7xxx-play uses libavdevice, libavformat, libavcodec and libswscale to
+ * decode the input, encode it to jpeg and display it with libam7xxx.
+ */
+
+#include <stdio.h>
+#include <stdint.h>
+#include <string.h>
+#include <signal.h>
+#include <getopt.h>
+
+#include <libavdevice/avdevice.h>
+#include <libavformat/avformat.h>
+#include <libswscale/swscale.h>
+
+#include <am7xxx.h>
+
+static unsigned int run = 1;
+
+struct video_input_ctx {
+       AVFormatContext *format_ctx;
+       AVCodecContext  *codec_ctx;
+       int video_stream_index;
+};
+
+static int video_input_init(struct video_input_ctx *input_ctx,
+                           const char *input_format_string,
+                           const char *input_path,
+                           AVDictionary **input_options)
+{
+       AVInputFormat *input_format = NULL;
+       AVFormatContext *input_format_ctx;
+       AVCodecContext *input_codec_ctx;
+       AVCodec *input_codec;
+       int video_index;
+       unsigned int i;
+       int ret;
+
+       avdevice_register_all();
+       avcodec_register_all();
+       av_register_all();
+
+       if (input_format_string) {
+               /* find the desired input format */
+               input_format = av_find_input_format(input_format_string);
+               if (input_format == NULL) {
+                       fprintf(stderr, "cannot find input format\n");
+                       ret = -ENODEV;
+                       goto out;
+               }
+       }
+
+       if (input_path == NULL) {
+               fprintf(stderr, "input_path must not be NULL!\n");
+               ret = -EINVAL;
+               goto out;
+       }
+
+       /* open the input format/device */
+       input_format_ctx = NULL;
+       ret = avformat_open_input(&input_format_ctx,
+                                 input_path,
+                                 input_format,
+                                 input_options);
+       if (ret < 0) {
+               fprintf(stderr, "cannot open input format/device\n");
+               goto out;
+       }
+
+       /* get information on the input stream (e.g. format, bitrate, framerate) */
+       ret = avformat_find_stream_info(input_format_ctx, NULL);
+       if (ret < 0) {
+               fprintf(stderr, "cannot get information on the stream\n");
+               goto cleanup;
+       }
+
+       /* dump what was found */
+       av_dump_format(input_format_ctx, 0, input_path, 0);
+
+       /* look for the first video_stream */
+       video_index = -1;
+       for (i = 0; i < input_format_ctx->nb_streams; i++)
+               if (input_format_ctx->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
+                       video_index = i;
+                       break;
+               }
+       if (video_index == -1) {
+               fprintf(stderr, "cannot find any video streams\n");
+               ret = -ENOTSUP;
+               goto cleanup;
+       }
+
+       /* get a pointer to the codec context for the video stream */
+       input_codec_ctx = input_format_ctx->streams[video_index]->codec;
+       if (input_codec_ctx == NULL) {
+               fprintf(stderr, "input codec context is not valid\n");
+               ret = -ENOTSUP;
+               goto cleanup;
+       }
+
+       /* find the decoder for the video stream */
+       input_codec = avcodec_find_decoder(input_codec_ctx->codec_id);
+       if (input_codec == NULL) {
+               fprintf(stderr, "input_codec is NULL!\n");
+               ret = -ENOTSUP;
+               goto cleanup;
+       }
+
+       /* open the decoder */
+       ret = avcodec_open2(input_codec_ctx, input_codec, NULL);
+       if (ret < 0) {
+               fprintf(stderr, "cannot open input codec\n");
+               ret = -ENOTSUP;
+               goto cleanup;
+       }
+
+       input_ctx->format_ctx = input_format_ctx;
+       input_ctx->codec_ctx = input_codec_ctx;
+       input_ctx->video_stream_index = video_index;
+
+       ret = 0;
+       goto out;
+
+cleanup:
+       avformat_close_input(&input_format_ctx);
+out:
+       av_dict_free(input_options);
+       *input_options = NULL;
+       return ret;
+}
+
+
+struct video_output_ctx {
+       AVCodecContext  *codec_ctx;
+       int raw_output;
+};
+
+static int video_output_init(struct video_output_ctx *output_ctx,
+                            struct video_input_ctx *input_ctx,
+                            unsigned int upscale,
+                            unsigned int quality,
+                            am7xxx_image_format image_format,
+                            am7xxx_device *dev)
+{
+       AVCodecContext *output_codec_ctx;
+       AVCodec *output_codec;
+       unsigned int new_output_width;
+       unsigned int new_output_height;
+       int ret;
+
+       if (input_ctx == NULL) {
+               fprintf(stderr, "input_ctx must not be NULL!\n");
+               ret = -EINVAL;
+               goto out;
+       }
+
+       /* create the encoder context */
+       output_codec_ctx = avcodec_alloc_context3(NULL);
+       if (output_codec_ctx == NULL) {
+               fprintf(stderr, "cannot allocate output codec context!\n");
+               ret = -ENOMEM;
+               goto out;
+       }
+
+       /* Calculate the new output dimension so the original picture is shown
+        * in its entirety */
+       ret = am7xxx_calc_scaled_image_dimensions(dev,
+                                                 upscale,
+                                                 (input_ctx->codec_ctx)->width,
+                                                 (input_ctx->codec_ctx)->height,
+                                                 &new_output_width,
+                                                 &new_output_height);
+       if (ret < 0) {
+               fprintf(stderr, "cannot calculate output dimension\n");
+               goto cleanup;
+       }
+
+       /* put sample parameters */
+       output_codec_ctx->bit_rate   = (input_ctx->codec_ctx)->bit_rate;
+       output_codec_ctx->width      = new_output_width;
+       output_codec_ctx->height     = new_output_height;
+       output_codec_ctx->time_base.num  = (input_ctx->codec_ctx)->time_base.num;
+       output_codec_ctx->time_base.den  = (input_ctx->codec_ctx)->time_base.den;
+
+       /* When the raw format is requested we don't actually need to setup
+        * and open a decoder
+        */
+       if (image_format == AM7XXX_IMAGE_FORMAT_NV12) {
+               fprintf(stdout, "using raw output format\n");
+               output_codec_ctx->pix_fmt    = PIX_FMT_NV12;
+               output_ctx->codec_ctx = output_codec_ctx;
+               output_ctx->raw_output = 1;
+               ret = 0;
+               goto out;
+       }
+
+       output_codec_ctx->pix_fmt    = PIX_FMT_YUVJ420P;
+       output_codec_ctx->codec_id   = CODEC_ID_MJPEG;
+       output_codec_ctx->codec_type = AVMEDIA_TYPE_VIDEO;
+
+       /* Set quality and other VBR settings */
+
+       /* @note: 'quality' is expected to be between 1 and 100, but a value
+        * between 0 to 99 has to be passed when calculating qmin and qmax.
+        * This way qmin and qmax will cover the range 1-FF_QUALITY_SCALE, and
+        * in particular they won't be 0, this is needed because they are used
+        * as divisor somewhere in the encoding process */
+       output_codec_ctx->qmin       = output_codec_ctx->qmax = ((100 - (quality - 1)) * FF_QUALITY_SCALE) / 100;
+       output_codec_ctx->mb_lmin    = output_codec_ctx->lmin = output_codec_ctx->qmin * FF_QP2LAMBDA;
+       output_codec_ctx->mb_lmax    = output_codec_ctx->lmax = output_codec_ctx->qmax * FF_QP2LAMBDA;
+       output_codec_ctx->flags      |= CODEC_FLAG_QSCALE;
+       output_codec_ctx->global_quality = output_codec_ctx->qmin * FF_QP2LAMBDA;
+
+       /* find the encoder */
+       output_codec = avcodec_find_encoder(output_codec_ctx->codec_id);
+       if (output_codec == NULL) {
+               fprintf(stderr, "cannot find output codec!\n");
+               ret = -ENOTSUP;
+               goto cleanup;
+       }
+
+       /* open the codec */
+       ret = avcodec_open2(output_codec_ctx, output_codec, NULL);
+       if (ret < 0) {
+               fprintf(stderr, "could not open output codec!\n");
+               goto cleanup;
+       }
+
+       output_ctx->codec_ctx = output_codec_ctx;
+       output_ctx->raw_output = 0;
+
+       ret = 0;
+       goto out;
+
+cleanup:
+       avcodec_close(output_codec_ctx);
+       av_free(output_codec_ctx);
+out:
+       return ret;
+}
+
+
+static int am7xxx_play(const char *input_format_string,
+                      AVDictionary **input_options,
+                      const char *input_path,
+                      unsigned int rescale_method,
+                      unsigned int upscale,
+                      unsigned int quality,
+                      am7xxx_image_format image_format,
+                      am7xxx_device *dev)
+{
+       struct video_input_ctx input_ctx;
+       struct video_output_ctx output_ctx;
+       AVFrame *picture_raw;
+       AVFrame *picture_scaled;
+       int out_buf_size;
+       uint8_t *out_buf;
+       int out_picture_size;
+       struct SwsContext *sw_scale_ctx;
+       AVPacket packet;
+       int got_picture;
+       int ret = 0;
+
+       ret = video_input_init(&input_ctx, input_format_string, input_path, input_options);
+       if (ret < 0) {
+               fprintf(stderr, "cannot initialize input\n");
+               goto out;
+       }
+
+       ret = video_output_init(&output_ctx, &input_ctx, upscale, quality, image_format, dev);
+       if (ret < 0) {
+               fprintf(stderr, "cannot initialize input\n");
+               goto cleanup_input;
+       }
+
+       /* allocate an input frame */
+       picture_raw = avcodec_alloc_frame();
+       if (picture_raw == NULL) {
+               fprintf(stderr, "cannot allocate the raw picture frame!\n");
+               ret = -ENOMEM;
+               goto cleanup_output;
+       }
+
+       /* allocate output frame */
+       picture_scaled = avcodec_alloc_frame();
+       if (picture_scaled == NULL) {
+               fprintf(stderr, "cannot allocate the scaled picture!\n");
+               ret = -ENOMEM;
+               goto cleanup_picture_raw;
+       }
+
+       /* calculate the bytes needed for the output image and create buffer for the output image */
+       out_buf_size = avpicture_get_size((output_ctx.codec_ctx)->pix_fmt,
+                                         (output_ctx.codec_ctx)->width,
+                                         (output_ctx.codec_ctx)->height);
+       out_buf = av_malloc(out_buf_size * sizeof(uint8_t));
+       if (out_buf == NULL) {
+               fprintf(stderr, "cannot allocate output data buffer!\n");
+               ret = -ENOMEM;
+               goto cleanup_picture_scaled;
+       }
+
+       /* assign appropriate parts of buffer to image planes in picture_scaled */
+       avpicture_fill((AVPicture *)picture_scaled,
+                      out_buf,
+                      (output_ctx.codec_ctx)->pix_fmt,
+                      (output_ctx.codec_ctx)->width,
+                      (output_ctx.codec_ctx)->height);
+
+       sw_scale_ctx = sws_getCachedContext(NULL,
+                                           (input_ctx.codec_ctx)->width,
+                                           (input_ctx.codec_ctx)->height,
+                                           (input_ctx.codec_ctx)->pix_fmt,
+                                           (output_ctx.codec_ctx)->width,
+                                           (output_ctx.codec_ctx)->height,
+                                           (output_ctx.codec_ctx)->pix_fmt,
+                                           rescale_method,
+                                           NULL, NULL, NULL);
+       if (sw_scale_ctx == NULL) {
+               fprintf(stderr, "cannot set up the rescaling context!\n");
+               ret = -EINVAL;
+               goto cleanup_out_buf;
+       }
+
+       while (run) {
+               /* read packet */
+               ret = av_read_frame(input_ctx.format_ctx, &packet);
+               if (ret < 0) {
+                       if (ret == (int)AVERROR_EOF || input_ctx.format_ctx->pb->eof_reached)
+                               ret = 0;
+                       else
+                               fprintf(stderr, "av_read_frame failed, EOF?\n");
+                       run = 0;
+                       goto end_while;
+               }
+
+               if (packet.stream_index != input_ctx.video_stream_index) {
+                       /* that is more or less a "continue", but there is
+                        * still the packet to free */
+                       goto end_while;
+               }
+
+               /* decode */
+               got_picture = 0;
+               ret = avcodec_decode_video2(input_ctx.codec_ctx, picture_raw, &got_picture, &packet);
+               if (ret < 0) {
+                       fprintf(stderr, "cannot decode video\n");
+                       run = 0;
+                       goto end_while;
+               }
+
+               /* if we get the complete frame */
+               if (got_picture) {
+                       /* convert it to YUV */
+                       sws_scale(sw_scale_ctx,
+                                 (const uint8_t * const*)picture_raw->data,
+                                 picture_raw->linesize,
+                                 0,
+                                 (input_ctx.codec_ctx)->height,
+                                 picture_scaled->data,
+                                 picture_scaled->linesize);
+
+                       if (output_ctx.raw_output) {
+                               out_picture_size = out_buf_size;
+                       } else {
+                               picture_scaled->quality = (output_ctx.codec_ctx)->global_quality;
+                               /* TODO: switch to avcodec_encode_video2() eventually */
+                               out_picture_size = avcodec_encode_video(output_ctx.codec_ctx,
+                                                                       out_buf,
+                                                                       out_buf_size,
+                                                                       picture_scaled);
+                               if (out_picture_size < 0) {
+                                       fprintf(stderr, "cannot encode video\n");
+                                       ret = out_picture_size;
+                                       run = 0;
+                                       goto end_while;
+                               }
+                       }
+
+#ifdef DEBUG
+                       char filename[NAME_MAX];
+                       FILE *file;
+                       if (!output_ctx.raw_output)
+                               snprintf(filename, NAME_MAX, "out_q%03d.jpg", quality);
+                       else
+                               snprintf(filename, NAME_MAX, "out.raw");
+                       file = fopen(filename, "wb");
+                       fwrite(out_buf, 1, out_picture_size, file);
+                       fclose(file);
+#endif
+
+                       ret = am7xxx_send_image(dev,
+                                               image_format,
+                                               (output_ctx.codec_ctx)->width,
+                                               (output_ctx.codec_ctx)->height,
+                                               out_buf,
+                                               out_picture_size);
+                       if (ret < 0) {
+                               perror("am7xxx_send_image");
+                               run = 0;
+                               goto end_while;
+                       }
+               }
+end_while:
+               av_free_packet(&packet);
+       }
+
+       sws_freeContext(sw_scale_ctx);
+cleanup_out_buf:
+       av_free(out_buf);
+cleanup_picture_scaled:
+       av_free(picture_scaled);
+cleanup_picture_raw:
+       av_free(picture_raw);
+
+cleanup_output:
+       /* av_free is needed as well,
+        * see http://libav.org/doxygen/master/avcodec_8h.html#a5d7440cd7ea195bd0b14f21a00ef36dd
+        */
+       avcodec_close(output_ctx.codec_ctx);
+       av_free(output_ctx.codec_ctx);
+
+cleanup_input:
+       avcodec_close(input_ctx.codec_ctx);
+       avformat_close_input(&(input_ctx.format_ctx));
+
+out:
+       return ret;
+}
+
+#ifdef HAVE_XCB
+#include <xcb/xcb.h>
+static int x_get_screen_dimensions(const char *displayname, int *width, int *height)
+{
+       int i, screen_number;
+       xcb_connection_t *connection;
+       const xcb_setup_t *setup;
+       xcb_screen_iterator_t iter;
+
+       connection = xcb_connect(displayname, &screen_number);
+       if (xcb_connection_has_error(connection)) {
+               fprintf(stderr, "Cannot open a connection to %s\n", displayname);
+               return -EINVAL;
+       }
+
+       setup = xcb_get_setup(connection);
+       if (setup == NULL) {
+               fprintf(stderr, "Cannot get setup for %s\n", displayname);
+               xcb_disconnect(connection);
+               return -EINVAL;
+       }
+
+       iter = xcb_setup_roots_iterator(setup);
+       for (i = 0; i < screen_number; ++i) {
+               xcb_screen_next(&iter);
+       }
+
+       xcb_screen_t *screen = iter.data;
+
+       *width = screen->width_in_pixels;
+       *height = screen->height_in_pixels;
+
+       xcb_disconnect(connection);
+
+       return 0;
+}
+
+static char *get_x_screen_size(const char *input_path)
+{
+       int len;
+       int width;
+       int height;
+       char *screen_size;
+       int ret;
+
+       ret = x_get_screen_dimensions(input_path, &width, &height);
+       if (ret < 0) {
+               fprintf(stderr, "Cannot get screen dimensions for %s\n", input_path);
+               return NULL;
+       }
+
+       len = snprintf(NULL, 0, "%dx%d", width, height);
+
+       screen_size = malloc((len + 1) * sizeof(char));
+       if (screen_size == NULL) {
+               perror("malloc");
+               return NULL;
+       }
+
+       len = snprintf(screen_size, len + 1, "%dx%d", width, height);
+       if (len < 0) {
+               free(screen_size);
+               screen_size = NULL;
+               return NULL;
+       }
+       return screen_size;
+}
+#else
+static char *get_x_screen_size(const char *input_path)
+{
+       (void) input_path;
+       fprintf(stderr, "%s: fallback implementation\n", __func__);
+       return strdup("vga");
+}
+#endif
+
+static void unset_run(int signo)
+{
+       (void) signo;
+       run = 0;
+}
+
+static int set_signal_handler(void (*signal_handler)(int))
+{
+       struct sigaction new_action;
+       struct sigaction old_action;
+       int ret = 0;
+
+       new_action.sa_handler = signal_handler;
+       sigemptyset(&new_action.sa_mask);
+       new_action.sa_flags = 0;
+
+       ret = sigaction(SIGINT, NULL, &old_action);
+       if (ret < 0) {
+               perror("sigaction on old_action");
+               goto out;
+       }
+
+       if (old_action.sa_handler != SIG_IGN) {
+               ret = sigaction(SIGINT, &new_action, NULL);
+               if (ret < 0) {
+                       perror("sigaction on new_action");
+                       goto out;
+               }
+       }
+
+out:
+       return ret;
+}
+
+static void usage(char *name)
+{
+       printf("usage: %s [OPTIONS]\n\n", name);
+       printf("OPTIONS:\n");
+       printf("\t-f <input format>\tthe input device format\n");
+       printf("\t-i <input path>\t\tthe input path\n");
+       printf("\t-o <options>\t\ta comma separated list of input format options\n");
+       printf("\t\t\t\tEXAMPLE:\n");
+       printf("\t\t\t\t\t-o draw_mouse=1,framerate=100,video_size=800x480\n");
+       printf("\t-s <scaling method>\tthe rescaling method (see swscale.h)\n");
+       printf("\t-u \t\t\tupscale the image if smaller than the display dimensions\n");
+       printf("\t-F <format>\t\tthe image format to use (default is JPEG)\n");
+       printf("\t\t\t\tSUPPORTED FORMATS:\n");
+       printf("\t\t\t\t\t1 - JPEG\n");
+       printf("\t\t\t\t\t2 - NV12\n");
+       printf("\t-q <quality>\t\tquality of jpeg sent to the device, between 1 and 100\n");
+       printf("\t-l <log level>\t\tthe verbosity level of libam7xxx output (0-5)\n");
+       printf("\t-p <power level>\tpower level of device, between %x (off) and %x (maximum)\n", AM7XXX_POWER_OFF, AM7XXX_POWER_TURBO);
+       printf("\t\t\t\tWARNING: Level 2 and greater require the master AND\n\t\t\t\t\t the slave connector to be plugged in.\n");
+       printf("\t-h \t\t\tthis help message\n");
+       printf("\n\nEXAMPLES OF USE:\n");
+       printf("\t%s -f x11grab -i :0.0 -o video_size=800x480\n", name);
+       printf("\t%s -f fbdev -i /dev/fb0\n", name);
+       printf("\t%s -f video4linux2 -i /dev/video0 -o video_size=320x240,frame_rate=100 -u -q 90\n", name);
+       printf("\t%s -i http://download.blender.org/peach/bigbuckbunny_movies/BigBuckBunny_640x360.m4v\n", name);
+}
+
+int main(int argc, char *argv[])
+{
+       int ret;
+       int opt;
+       char *subopts;
+       char *subopts_saved;
+       char *subopt;
+       char *input_format_string = NULL;
+       AVDictionary *options = NULL;
+       char *input_path = NULL;
+       unsigned int rescale_method = SWS_BICUBIC;
+       unsigned int upscale = 0;
+       unsigned int quality = 95;
+       int log_level = AM7XXX_LOG_INFO;
+       am7xxx_power_mode power_mode = AM7XXX_POWER_LOW;
+       int format = AM7XXX_IMAGE_FORMAT_JPEG;
+       am7xxx_context *ctx;
+       am7xxx_device *dev;
+
+       while ((opt = getopt(argc, argv, "f:i:o:s:uF:q:l:hp:")) != -1) {
+               switch (opt) {
+               case 'f':
+                       input_format_string = strdup(optarg);
+                       break;
+               case 'i':
+                       input_path = strdup(optarg);
+                       break;
+               case 'o':
+                       /*
+                        * parse suboptions, the expected format is something
+                        * like:
+                        *   draw_mouse=1,framerate=100,video_size=800x480
+                        */
+                       subopts = subopts_saved = strdup(optarg);
+                       while((subopt = strtok_r(subopts, ",", &subopts))) {
+                               char *subopt_name = strtok_r(subopt, "=", &subopt);
+                               char *subopt_value = strtok_r(NULL, "", &subopt);
+                               if (subopt_value == NULL) {
+                                       fprintf(stderr, "invalid suboption: %s\n", subopt_name);
+                                       continue;
+                               }
+                               av_dict_set(&options, subopt_name, subopt_value, 0);
+                       }
+                       free(subopts_saved);
+                       break;
+               case 's':
+                       rescale_method = atoi(optarg);
+                       switch(rescale_method) {
+                       case SWS_FAST_BILINEAR:
+                       case SWS_BILINEAR:
+                       case SWS_BICUBIC:
+                       case SWS_X:
+                       case SWS_POINT:
+                       case SWS_AREA:
+                       case SWS_BICUBLIN:
+                       case SWS_GAUSS:
+                       case SWS_SINC:
+                       case SWS_LANCZOS:
+                       case SWS_SPLINE:
+                               break;
+                       default:
+                               fprintf(stderr, "Unsupported rescale method\n");
+                               ret = -EINVAL;
+                               goto out;
+                       }
+                       break;
+               case 'u':
+                       upscale = 1;
+                       break;
+               case 'F':
+                       format = atoi(optarg);
+                       switch(format) {
+                       case AM7XXX_IMAGE_FORMAT_JPEG:
+                               fprintf(stdout, "JPEG format\n");
+                               break;
+                       case AM7XXX_IMAGE_FORMAT_NV12:
+                               fprintf(stdout, "NV12 format\n");
+                               break;
+                       default:
+                               fprintf(stderr, "Unsupported format\n");
+                               ret = -EINVAL;
+                               goto out;
+                       }
+                       break;
+               case 'q':
+                       quality = atoi(optarg);
+                       if (quality < 1 || quality > 100) {
+                               fprintf(stderr, "Invalid quality value, must be between 1 and 100\n");
+                               ret = -EINVAL;
+                               goto out;
+                       }
+                       break;
+               case 'l':
+                       log_level = atoi(optarg);
+                       if (log_level < AM7XXX_LOG_FATAL || log_level > AM7XXX_LOG_TRACE) {
+                               fprintf(stderr, "Unsupported log level, falling back to AM7XXX_LOG_ERROR\n");
+                               log_level = AM7XXX_LOG_ERROR;
+                       }
+                       break;
+               case 'h':
+                       usage(argv[0]);
+                       ret = 0;
+                       goto out;
+                       break;
+               case 'p':
+                       power_mode = atoi(optarg);
+                       switch(power_mode) {
+                       case AM7XXX_POWER_OFF:
+                       case AM7XXX_POWER_LOW:
+                       case AM7XXX_POWER_MIDDLE:
+                       case AM7XXX_POWER_HIGH:
+                       case AM7XXX_POWER_TURBO:
+                               fprintf(stdout, "Power mode: %x\n", power_mode);
+                               break;
+                       default:
+                               fprintf(stderr, "Invalid power mode value, must be between %x and %x\n", AM7XXX_POWER_OFF, AM7XXX_POWER_TURBO);
+                               ret = -EINVAL;
+                               goto out;
+                       }
+                       break;
+               default: /* '?' */
+                       usage(argv[0]);
+                       ret = -EINVAL;
+                       goto out;
+               }
+       }
+
+       if (input_path == NULL) {
+               fprintf(stderr, "The -i option must always be passed\n");
+               ret = -EINVAL;
+               goto out;
+       }
+
+       /*
+        * When the input format is 'x11grab' set some useful fallback options
+        * if not supplied by the user, in particular grab full screen
+        */
+       if (input_format_string && strcmp(input_format_string, "x11grab") == 0) {
+               char *video_size;
+
+               video_size = get_x_screen_size(input_path);
+
+               if (!av_dict_get(options, "video_size", NULL, 0))
+                       av_dict_set(&options, "video_size", video_size, 0);
+
+               if (!av_dict_get(options, "framerate", NULL, 0))
+                       av_dict_set(&options, "framerate", "60", 0);
+
+               if (!av_dict_get(options, "draw_mouse", NULL, 0))
+                       av_dict_set(&options, "draw_mouse",  "1", 0);
+
+               free(video_size);
+       }
+
+       ret = set_signal_handler(unset_run);
+       if (ret < 0) {
+               perror("sigaction");
+               goto out;
+       }
+
+       ret = am7xxx_init(&ctx);
+       if (ret < 0) {
+               perror("am7xxx_init");
+               goto out;
+       }
+
+       am7xxx_set_log_level(ctx, log_level);
+
+       ret = am7xxx_open_device(ctx, &dev, 0);
+       if (ret < 0) {
+               perror("am7xxx_open_device");
+               goto cleanup;
+       }
+
+       ret = am7xxx_set_power_mode(dev, power_mode);
+       if (ret < 0) {
+               perror("am7xxx_set_power_mode");
+               goto cleanup;
+       }
+
+       ret = am7xxx_play(input_format_string,
+                         &options,
+                         input_path,
+                         rescale_method,
+                         upscale,
+                         quality,
+                         format,
+                         dev);
+       if (ret < 0) {
+               fprintf(stderr, "am7xxx_play failed\n");
+               goto cleanup;
+       }
+
+cleanup:
+       am7xxx_shutdown(ctx);
+out:
+       av_dict_free(&options);
+       free(input_path);
+       free(input_format_string);
+       return ret;
+}
diff --git a/examples/picoproj.c b/examples/picoproj.c
new file mode 100644 (file)
index 0000000..7ae1296
--- /dev/null
@@ -0,0 +1,218 @@
+/* picoproj - test program for libam7xxx
+ *
+ * Copyright (C) 2012  Antonio Ospite <ospite@studenti.unina.it>
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program.  If not, see <http://www.gnu.org/licenses/>.
+ */
+
+/**
+ * @example examples/picoproj.c
+ * A minimal example to show how to use libam7xxx to display a static image.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/mman.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <unistd.h>
+
+#include "am7xxx.h"
+
+static void usage(char *name)
+{
+       printf("usage: %s [OPTIONS]\n\n", name);
+       printf("OPTIONS:\n");
+       printf("\t-f <filename>\t\tthe image file to upload\n");
+       printf("\t-F <format>\t\tthe image format to use (default is JPEG)\n");
+       printf("\t\t\t\tSUPPORTED FORMATS:\n");
+       printf("\t\t\t\t\t1 - JPEG\n");
+       printf("\t\t\t\t\t2 - NV12\n");
+       printf("\t-l <log level>\t\tthe verbosity level of libam7xxx output (0-5)\n");
+       printf("\t-W <image width>\tthe width of the image to upload\n");
+       printf("\t-H <image height>\tthe height of the image to upload\n");
+       printf("\t-h \t\t\tthis help message\n");
+       printf("\n\nEXAMPLE OF USE:\n");
+       printf("\t%s -f file.jpg -F 1 -l 5 -W 800 -H 480\n", name);
+}
+
+int main(int argc, char *argv[])
+{
+       int ret;
+       int exit_code = EXIT_SUCCESS;
+       int opt;
+
+       char filename[FILENAME_MAX] = {0};
+       int image_fd;
+       struct stat st;
+       am7xxx_context *ctx;
+       am7xxx_device *dev;
+       int log_level = AM7XXX_LOG_INFO;
+       int format = AM7XXX_IMAGE_FORMAT_JPEG;
+       int width = 800;
+       int height = 480;
+       unsigned char *image;
+       unsigned int size;
+       am7xxx_device_info device_info;
+
+       while ((opt = getopt(argc, argv, "f:F:l:W:H:h")) != -1) {
+               switch (opt) {
+               case 'f':
+                       strncpy(filename, optarg, FILENAME_MAX);
+                       break;
+               case 'F':
+                       format = atoi(optarg);
+                       switch(format) {
+                       case AM7XXX_IMAGE_FORMAT_JPEG:
+                               fprintf(stdout, "JPEG format\n");
+                               break;
+                       case AM7XXX_IMAGE_FORMAT_NV12:
+                               fprintf(stdout, "NV12 format\n");
+                               break;
+                       default:
+                               fprintf(stderr, "Unsupported format\n");
+                               exit(EXIT_FAILURE);
+                       }
+                       break;
+               case 'l':
+                       log_level = atoi(optarg);
+                       if (log_level < AM7XXX_LOG_FATAL || log_level > AM7XXX_LOG_TRACE) {
+                               fprintf(stderr, "Unsupported log level, falling back to AM7XXX_LOG_ERROR\n");
+                               log_level = AM7XXX_LOG_ERROR;
+                       }
+                       break;
+               case 'W':
+                       width = atoi(optarg);
+                       if (width < 0) {
+                               fprintf(stderr, "Unsupported width\n");
+                               exit(EXIT_FAILURE);
+                       }
+                       break;
+               case 'H':
+                       height = atoi(optarg);
+                       if (height < 0) {
+                               fprintf(stderr, "Unsupported height\n");
+                               exit(EXIT_FAILURE);
+                       }
+                       break;
+               case 'h':
+                       usage(argv[0]);
+                       exit(EXIT_SUCCESS);
+                       break;
+               default: /* '?' */
+                       usage(argv[0]);
+                       exit(EXIT_FAILURE);
+               }
+       }
+
+       if (filename[0] == '\0') {
+               fprintf(stderr, "An image file MUST be specified.\n");
+               exit_code = EXIT_FAILURE;
+               goto out;
+       }
+
+       image_fd = open(filename, O_RDONLY);
+       if (image_fd < 0) {
+               perror("open");
+               exit_code = EXIT_FAILURE;
+               goto out;
+       }
+       if (fstat(image_fd, &st) < 0) {
+               perror("fstat");
+               exit_code = EXIT_FAILURE;
+               goto out_close_image_fd;
+       }
+       size = st.st_size;
+
+       image = mmap(NULL, st.st_size, PROT_READ, MAP_SHARED, image_fd, 0);
+       if (image == NULL) {
+               perror("mmap");
+               exit_code = EXIT_FAILURE;
+               goto out_close_image_fd;
+       }
+
+       ret = am7xxx_init(&ctx);
+       if (ret < 0) {
+               perror("am7xxx_init");
+               exit_code = EXIT_FAILURE;
+               goto out_munmap;
+       }
+
+       am7xxx_set_log_level(ctx, log_level);
+
+       ret = am7xxx_open_device(ctx, &dev, 0);
+       if (ret < 0) {
+               perror("am7xxx_open_device");
+               exit_code = EXIT_FAILURE;
+               goto cleanup;
+       }
+
+
+       ret = am7xxx_close_device(dev);
+       if (ret < 0) {
+               perror("am7xxx_close_device");
+               exit_code = EXIT_FAILURE;
+               goto cleanup;
+       }
+
+       ret = am7xxx_open_device(ctx, &dev, 0);
+       if (ret < 0) {
+               perror("am7xxx_open_device");
+               exit_code = EXIT_FAILURE;
+               goto cleanup;
+       }
+
+       ret = am7xxx_get_device_info(dev, &device_info);
+       if (ret < 0) {
+               perror("am7xxx_get_info");
+               exit_code = EXIT_FAILURE;
+               goto cleanup;
+       }
+       printf("Native resolution: %dx%d\n",
+              device_info.native_width, device_info.native_height);
+
+       ret = am7xxx_set_power_mode(dev, AM7XXX_POWER_LOW);
+       if (ret < 0) {
+               perror("am7xxx_set_power_mode");
+               exit_code = EXIT_FAILURE;
+               goto cleanup;
+       }
+
+       ret = am7xxx_send_image(dev, format, width, height, image, size);
+       if (ret < 0) {
+               perror("am7xxx_send_image");
+               exit_code = EXIT_FAILURE;
+               goto cleanup;
+       }
+
+       exit_code = EXIT_SUCCESS;
+
+cleanup:
+       am7xxx_shutdown(ctx);
+
+out_munmap:
+       ret = munmap(image, size);
+       if (ret < 0)
+               perror("munmap");
+
+out_close_image_fd:
+       ret = close(image_fd);
+       if (ret < 0)
+               perror("close");
+
+out:
+       exit(exit_code);
+}
index 1228201..e09a282 100644 (file)
@@ -1,5 +1,4 @@
 add_definitions("-D_BSD_SOURCE") # for htole32()
-add_definitions("-D_POSIX_C_SOURCE=2") # for getopt()
 
 # Find packages needed to build library
 find_package(libusb-1.0 REQUIRED)
@@ -23,8 +22,10 @@ endif()
 install(TARGETS am7xxx-static
    DESTINATION "${CMAKE_INSTALL_PREFIX}/lib")
 
-target_link_libraries(am7xxx ${LIBUSB_1_LIBRARIES})
-target_link_libraries(am7xxx-static ${LIBUSB_1_LIBRARIES})
+find_library(MATH_LIB m)
+
+target_link_libraries(am7xxx ${MATH_LIB} ${LIBUSB_1_LIBRARIES})
+target_link_libraries(am7xxx-static ${MATH_LIB} ${LIBUSB_1_LIBRARIES})
 
 # Install the header files
 install(FILES "am7xxx.h"
@@ -32,13 +33,7 @@ install(FILES "am7xxx.h"
 
 if(UNIX AND NOT APPLE)
   # Produce a pkg-config file for linking against the shared lib
-  configure_file ("libam7xxx.pc.in" "libam7xxx.pc" @ONLY)
+  configure_file("libam7xxx.pc.in" "libam7xxx.pc" @ONLY)
   install(FILES "${CMAKE_CURRENT_BINARY_DIR}/libam7xxx.pc"
     DESTINATION "${CMAKE_INSTALL_PREFIX}/lib/pkgconfig")
 endif()
-
-# Build the test app
-add_executable(picoproj picoproj.c)
-target_link_libraries(picoproj am7xxx)
-install(TARGETS picoproj
-  DESTINATION "${CMAKE_INSTALL_PREFIX}/bin")
index c02b539..1035e23 100644 (file)
 
 #include <stdio.h>
 #include <stdlib.h>
+#include <string.h>
+#include <stdarg.h>
 #include <errno.h>
+#include <libusb.h>
+#include <math.h>
 
 #include "am7xxx.h"
 #include "serialize.h"
 
-#define AM7XXX_VENDOR_ID  0x1de1
-#define AM7XXX_PRODUCT_ID 0xc101
+#define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
+
+/* If we're not using GNU C, elide __attribute__
+ * taken from: http://unixwiz.net/techtips/gnu-c-attributes.html)
+ */
+#ifndef __GNUC__
+#  define  __attribute__(x)  /*NOTHING*/
+#endif
+
+static void log_message(am7xxx_context *ctx,
+                       int level,
+                       const char *function,
+                       int line,
+                       const char *fmt,
+                       ...) __attribute__ ((format (printf, 5, 6)));
+
+#define fatal(...)        log_message(NULL, AM7XXX_LOG_FATAL,   __func__, __LINE__, __VA_ARGS__)
+#define error(ctx, ...)   log_message(ctx,  AM7XXX_LOG_ERROR,   __func__, __LINE__, __VA_ARGS__)
+#define warning(ctx, ...) log_message(ctx,  AM7XXX_LOG_WARNING, __func__, 0,        __VA_ARGS__)
+#define info(ctx, ...)    log_message(ctx,  AM7XXX_LOG_INFO,    __func__, 0,        __VA_ARGS__)
+#define debug(ctx, ...)   log_message(ctx,  AM7XXX_LOG_DEBUG,   __func__, 0,        __VA_ARGS__)
+#define trace(ctx, ...)   log_message(ctx,  AM7XXX_LOG_TRACE,   NULL,     0,        __VA_ARGS__)
+
+struct am7xxx_usb_device_descriptor {
+       const char *name;
+       uint16_t vendor_id;
+       uint16_t product_id;
+};
+
+static struct am7xxx_usb_device_descriptor supported_devices[] = {
+       {
+               .name       = "Acer C110",
+               .vendor_id  = 0x1de1,
+               .product_id = 0xc101,
+       },
+       {
+               .name       = "Philips/Sagemcom PicoPix 1020",
+               .vendor_id  = 0x21e7,
+               .product_id = 0x000e,
+       },
+};
+
+/* The header size on the wire is known to be always 24 bytes, regardless of
+ * the memory configuration enforced by different architectures or compilers
+ * for struct am7xxx_header
+ */
+#define AM7XXX_HEADER_WIRE_SIZE 24
+
+struct _am7xxx_device {
+       libusb_device_handle *usb_device;
+       uint8_t buffer[AM7XXX_HEADER_WIRE_SIZE];
+       am7xxx_context *ctx;
+       am7xxx_device *next;
+};
+
+struct _am7xxx_context {
+       libusb_context *usb_context;
+       int log_level;
+       am7xxx_device *devices_list;
+};
 
 typedef enum {
        AM7XXX_PACKET_TYPE_DEVINFO = 0x01,
@@ -70,12 +132,6 @@ struct am7xxx_power_header {
  * 04 00 00 00 00 0c ff ff 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
  */
 
-/* The header size on the wire is known to be always 24 bytes, regardless of
- * the memory configuration enforced by different architechtures or compilers
- * for struct am7xxx_header
- */
-#define AM7XXX_HEADER_WIRE_SIZE 24
-
 struct am7xxx_header {
        uint32_t packet_type;
        uint8_t unknown0;
@@ -91,71 +147,72 @@ struct am7xxx_header {
 };
 
 
-static void dump_devinfo_header(struct am7xxx_devinfo_header *d)
+#ifdef DEBUG
+static void debug_dump_devinfo_header(am7xxx_context *ctx, struct am7xxx_devinfo_header *d)
 {
-       if (d == NULL)
+       if (ctx == NULL || d == NULL)
                return;
 
-       printf("Info header:\n");
-       printf("\tnative_width:  0x%08x (%u)\n", d->native_width, d->native_width);
-       printf("\tnative_height: 0x%08x (%u)\n", d->native_height, d->native_height);
-       printf("\tunknown0:      0x%08x (%u)\n", d->unknown0, d->unknown0);
-       printf("\tunknown1:      0x%08x (%u)\n", d->unknown1, d->unknown1);
+       debug(ctx, "Info header:\n");
+       debug(ctx, "\tnative_width:  0x%08x (%u)\n", d->native_width, d->native_width);
+       debug(ctx, "\tnative_height: 0x%08x (%u)\n", d->native_height, d->native_height);
+       debug(ctx, "\tunknown0:      0x%08x (%u)\n", d->unknown0, d->unknown0);
+       debug(ctx, "\tunknown1:      0x%08x (%u)\n", d->unknown1, d->unknown1);
 }
 
-static void dump_image_header(struct am7xxx_image_header *i)
+static void debug_dump_image_header(am7xxx_context *ctx, struct am7xxx_image_header *i)
 {
-       if (i == NULL)
+       if (ctx == NULL || i == NULL)
                return;
 
-       printf("Image header:\n");
-       printf("\tformat:     0x%08x (%u)\n", i->format, i->format);
-       printf("\twidth:      0x%08x (%u)\n", i->width, i->width);
-       printf("\theight:     0x%08x (%u)\n", i->height, i->height);
-       printf("\timage size: 0x%08x (%u)\n", i->image_size, i->image_size);
+       debug(ctx, "Image header:\n");
+       debug(ctx, "\tformat:     0x%08x (%u)\n", i->format, i->format);
+       debug(ctx, "\twidth:      0x%08x (%u)\n", i->width, i->width);
+       debug(ctx, "\theight:     0x%08x (%u)\n", i->height, i->height);
+       debug(ctx, "\timage size: 0x%08x (%u)\n", i->image_size, i->image_size);
 }
 
-static void dump_power_header(struct am7xxx_power_header *p)
+static void debug_dump_power_header(am7xxx_context *ctx, struct am7xxx_power_header *p)
 {
-       if (p == NULL)
+       if (ctx == NULL || p == NULL)
                return;
 
-       printf("Power header:\n");
-       printf("\tbit2: 0x%08x (%u)\n", p->bit2, p->bit2);
-       printf("\tbit1: 0x%08x (%u)\n", p->bit1, p->bit1);
-       printf("\tbit0: 0x%08x (%u)\n", p->bit0, p->bit0);
+       debug(ctx, "Power header:\n");
+       debug(ctx, "\tbit2: 0x%08x (%u)\n", p->bit2, p->bit2);
+       debug(ctx, "\tbit1: 0x%08x (%u)\n", p->bit1, p->bit1);
+       debug(ctx, "\tbit0: 0x%08x (%u)\n", p->bit0, p->bit0);
 }
 
-static void dump_header(struct am7xxx_header *h)
+static void debug_dump_header(am7xxx_context *ctx, struct am7xxx_header *h)
 {
-       if (h == NULL)
+       if (ctx == NULL || h == NULL)
                return;
 
-       printf("packet_type:     0x%08x (%u)\n", h->packet_type, h->packet_type);
-       printf("unknown0:        0x%02hhx (%hhu)\n", h->unknown0, h->unknown0);
-       printf("header_data_len: 0x%02hhx (%hhu)\n", h->header_data_len, h->header_data_len);
-       printf("unknown2:        0x%02hhx (%hhu)\n", h->unknown2, h->unknown2);
-       printf("unknown3:        0x%02hhx (%hhu)\n", h->unknown3, h->unknown3);
+       debug(ctx, "BEGIN\n");
+       debug(ctx, "packet_type:     0x%08x (%u)\n", h->packet_type, h->packet_type);
+       debug(ctx, "unknown0:        0x%02hhx (%hhu)\n", h->unknown0, h->unknown0);
+       debug(ctx, "header_data_len: 0x%02hhx (%hhu)\n", h->header_data_len, h->header_data_len);
+       debug(ctx, "unknown2:        0x%02hhx (%hhu)\n", h->unknown2, h->unknown2);
+       debug(ctx, "unknown3:        0x%02hhx (%hhu)\n", h->unknown3, h->unknown3);
 
        switch(h->packet_type) {
        case AM7XXX_PACKET_TYPE_DEVINFO:
-               dump_devinfo_header(&(h->header_data.devinfo));
+               debug_dump_devinfo_header(ctx, &(h->header_data.devinfo));
                break;
 
        case AM7XXX_PACKET_TYPE_IMAGE:
-               dump_image_header(&(h->header_data.image));
+               debug_dump_image_header(ctx, &(h->header_data.image));
                break;
 
        case AM7XXX_PACKET_TYPE_POWER:
-               dump_power_header(&(h->header_data.power));
+               debug_dump_power_header(ctx, &(h->header_data.power));
                break;
 
        default:
-               printf("Packet type not supported!\n");
+               debug(ctx, "Packet type not supported!\n");
                break;
        }
-
-       fflush(stdout);
+       debug(ctx, "END\n\n");
 }
 
 static inline unsigned int in_80chars(unsigned int i)
@@ -165,55 +222,68 @@ static inline unsigned int in_80chars(unsigned int i)
        return ((i+1) % (80/3));
 }
 
-static void dump_buffer(uint8_t *buffer, unsigned int len)
+static void trace_dump_buffer(am7xxx_context *ctx, const char *message,
+                             uint8_t *buffer, unsigned int len)
 {
        unsigned int i;
 
-       if (buffer == NULL || len == 0)
+       if (ctx == NULL || buffer == NULL || len == 0)
                return;
 
+       trace(ctx, "\n");
+       if (message)
+               trace(ctx, "%s\n", message);
+
        for (i = 0; i < len; i++) {
-               printf("%02hhX%c", buffer[i], (in_80chars(i) && (i < len - 1)) ? ' ' : '\n');
+               trace(ctx, "%02hhX%c", buffer[i], (in_80chars(i) && (i < len - 1)) ? ' ' : '\n');
        }
-       fflush(stdout);
+       trace(ctx, "\n");
+}
+#else
+static void debug_dump_header(am7xxx_context *ctx, struct am7xxx_header *h)
+{
+       (void)ctx;
+       (void)h;
 }
 
-static int read_data(am7xxx_device dev, uint8_t *buffer, unsigned int len)
+static void trace_dump_buffer(am7xxx_context *ctx, const char *message,
+                             uint8_t *buffer, unsigned int len)
+{
+       (void)ctx;
+       (void)message;
+       (void)buffer;
+       (void)len;
+}
+#endif /* DEBUG */
+
+static int read_data(am7xxx_device *dev, uint8_t *buffer, unsigned int len)
 {
        int ret;
        int transferred = 0;
 
-       ret = libusb_bulk_transfer(dev, 0x81, buffer, len, &transferred, 0);
+       ret = libusb_bulk_transfer(dev->usb_device, 0x81, buffer, len, &transferred, 0);
        if (ret != 0 || (unsigned int)transferred != len) {
-               fprintf(stderr, "Error: ret: %d\ttransferred: %d (expected %u)\n",
-                       ret, transferred, len);
+               error(dev->ctx, "ret: %d\ttransferred: %d (expected %u)\n",
+                     ret, transferred, len);
                return ret;
        }
 
-#if DEBUG
-       printf("\n<-- received\n");
-       dump_buffer(buffer, len);
-       printf("\n");
-#endif
+       trace_dump_buffer(dev->ctx, "<-- received", buffer, len);
 
        return 0;
 }
 
-static int send_data(am7xxx_device dev, uint8_t *buffer, unsigned int len)
+static int send_data(am7xxx_device *dev, uint8_t *buffer, unsigned int len)
 {
        int ret;
        int transferred = 0;
 
-#if DEBUG
-       printf("\nsending -->\n");
-       dump_buffer(buffer, len);
-       printf("\n");
-#endif
+       trace_dump_buffer(dev->ctx, "sending -->", buffer, len);
 
-       ret = libusb_bulk_transfer(dev, 1, buffer, len, &transferred, 0);
+       ret = libusb_bulk_transfer(dev->usb_device, 1, buffer, len, &transferred, 0);
        if (ret != 0 || (unsigned int)transferred != len) {
-               fprintf(stderr, "Error: ret: %d\ttransferred: %d (expected %u)\n",
-                       ret, transferred, len);
+               error(dev->ctx, "ret: %d\ttransferred: %d (expected %u)\n",
+                     ret, transferred, len);
                return ret;
        }
 
@@ -250,101 +320,341 @@ static void unserialize_header(uint8_t *buffer, struct am7xxx_header *h)
        h->header_data.data.field3 = get_le32(buffer_iterator);
 }
 
-static int read_header(am7xxx_device dev, struct am7xxx_header *h)
+static int read_header(am7xxx_device *dev, struct am7xxx_header *h)
 {
-       uint8_t *buffer;
        int ret;
 
-       buffer = calloc(AM7XXX_HEADER_WIRE_SIZE, 1);
-       if (buffer == NULL) {
-               perror("calloc buffer");
-               return -ENOMEM;
-       }
-
-       ret = read_data(dev, buffer, AM7XXX_HEADER_WIRE_SIZE);
+       ret = read_data(dev, dev->buffer, AM7XXX_HEADER_WIRE_SIZE);
        if (ret < 0)
                goto out;
 
-       unserialize_header(buffer, h);
+       unserialize_header(dev->buffer, h);
 
-#if DEBUG
-       printf("\n");
-       dump_header(h);
-       printf("\n");
-#endif
+       debug_dump_header(dev->ctx, h);
 
        ret = 0;
 
 out:
-       free(buffer);
        return ret;
 }
 
-static int send_header(am7xxx_device dev, struct am7xxx_header *h)
+static int send_header(am7xxx_device *dev, struct am7xxx_header *h)
 {
-       uint8_t *buffer;
        int ret;
 
-#if DEBUG
-       printf("\n");
-       dump_header(h);
-       printf("\n");
-#endif
+       debug_dump_header(dev->ctx, h);
+
+       serialize_header(h, dev->buffer);
+       ret = send_data(dev, dev->buffer, AM7XXX_HEADER_WIRE_SIZE);
+       if (ret < 0)
+               error(dev->ctx, "failed to send data\n");
+
+       return ret;
+}
+
+/* When level == AM7XXX_LOG_FATAL do not check the log_level from the context
+ * and print the message unconditionally, this makes it possible to print
+ * fatal messages even early on initialization, before the context has been
+ * set up */
+static void log_message(am7xxx_context *ctx,
+                       int level,
+                       const char *function,
+                       int line,
+                       const char *fmt,
+                       ...)
+{
+       va_list ap;
+
+       if (level == AM7XXX_LOG_FATAL || (ctx && level <= ctx->log_level)) {
+               if (function) {
+                       fprintf(stderr, "%s", function);
+                       if (line)
+                               fprintf(stderr, "[%d]", line);
+                       fprintf(stderr, ": ");
+               }
+
+               va_start(ap, fmt);
+               vfprintf(stderr, fmt, ap);
+               va_end(ap);
+       }
+
+       return;
+}
+
+static am7xxx_device *add_new_device(am7xxx_context *ctx)
+{
+       am7xxx_device **devices_list;
+       am7xxx_device *new_device;
+
+       if (ctx == NULL) {
+               fatal("context must not be NULL!\n");
+               return NULL;
+       }
+
+       devices_list = &(ctx->devices_list);
+
+       new_device = malloc(sizeof(*new_device));
+       if (new_device == NULL) {
+               fatal("cannot allocate a new device (%s)\n", strerror(errno));
+               return NULL;
+       }
+       memset(new_device, 0, sizeof(*new_device));
+
+       new_device->ctx = ctx;
+
+       if (*devices_list == NULL) {
+               *devices_list = new_device;
+       } else {
+               am7xxx_device *prev = *devices_list;
+               while (prev->next)
+                       prev = prev->next;
+               prev->next = new_device;
+       }
+       return new_device;
+}
+
+static am7xxx_device *find_device(am7xxx_context *ctx,
+                                 unsigned int device_index)
+{
+       unsigned int i = 0;
+       am7xxx_device *current;
+
+       if (ctx == NULL) {
+               fatal("context must not be NULL!\n");
+               return NULL;
+       }
+
+       current = ctx->devices_list;
+       while (current && i++ < device_index)
+               current = current->next;
+
+       return current;
+}
+
+typedef enum {
+       SCAN_OP_BUILD_DEVLIST,
+       SCAN_OP_OPEN_DEVICE,
+} scan_op;
+
+/**
+ * This is where the central logic of multi-device support is.
+ *
+ * When 'op' == SCAN_OP_BUILD_DEVLIST the parameters 'open_device_index' and
+ * 'dev' are ignored; the function returns 0 on success and a negative value
+ * on error.
+ *
+ * When 'op' == SCAN_OP_OPEN_DEVICE the function opens the supported USB
+ * device with index 'open_device_index' and returns the correspondent
+ * am7xxx_device in the 'dev' parameter; the function returns 0 on success,
+ * 1 if the device was already open and a negative value on error.
+ *
+ * NOTES:
+ * if scan_devices() fails when called with 'op' == SCAN_OP_BUILD_DEVLIST,
+ * the caller might want to call am7xxx_shutdown() in order to remove
+ * devices possibly added before the failure.
+ */
+static int scan_devices(am7xxx_context *ctx, scan_op op,
+                       unsigned int open_device_index, am7xxx_device **dev)
+{
+       int num_devices;
+       libusb_device** list;
+       unsigned int current_index;
+       int i;
+       int ret;
+
+       if (ctx == NULL) {
+               fatal("context must not be NULL!\n");
+               return -EINVAL;
+       }
+       if (op == SCAN_OP_BUILD_DEVLIST && ctx->devices_list != NULL) {
+               error(ctx, "device scan done already? Abort!\n");
+               return -EINVAL;
+       }
+
+       num_devices = libusb_get_device_list(ctx->usb_context, &list);
+       if (num_devices < 0) {
+               ret = -ENODEV;
+               goto out;
+       }
 
-       buffer = calloc(AM7XXX_HEADER_WIRE_SIZE, 1);
-       if (buffer == NULL) {
-               perror("calloc buffer");
-               return -ENOMEM;
+       current_index = 0;
+       for (i = 0; i < num_devices; i++) {
+               struct libusb_device_descriptor desc;
+               unsigned int j;
+
+               ret = libusb_get_device_descriptor(list[i], &desc);
+               if (ret < 0)
+                       continue;
+
+               for (j = 0; j < ARRAY_SIZE(supported_devices); j++) {
+                       if (desc.idVendor == supported_devices[j].vendor_id
+                           && desc.idProduct == supported_devices[j].product_id) {
+
+                               if (op == SCAN_OP_BUILD_DEVLIST) {
+                                       am7xxx_device *new_device;
+                                       info(ctx, "am7xxx device found, index: %d, name: %s\n",
+                                            current_index,
+                                            supported_devices[j].name);
+                                       new_device = add_new_device(ctx);
+                                       if (new_device == NULL) {
+                                               /* XXX, the caller may want
+                                                * to call am7xxx_shutdown() if
+                                                * we fail here, as we may have
+                                                * added some devices already
+                                                */
+                                               debug(ctx, "Cannot create a new device\n");
+                                               ret = -ENODEV;
+                                               goto out;
+                                       }
+                               } else if (op == SCAN_OP_OPEN_DEVICE &&
+                                          current_index == open_device_index) {
+
+                                       *dev = find_device(ctx, open_device_index);
+                                       if (*dev == NULL) {
+                                               ret = -ENODEV;
+                                               goto out;
+                                       }
+
+                                       /* the usb device has already been opened */
+                                       if ((*dev)->usb_device) {
+                                               debug(ctx, "(*dev)->usb_device already set\n");
+                                               ret = 1;
+                                               goto out;
+                                       }
+
+                                       ret = libusb_open(list[i], &((*dev)->usb_device));
+                                       if (ret < 0) {
+                                               debug(ctx, "libusb_open failed\n");
+                                               goto out;
+                                       }
+
+                                       libusb_set_configuration((*dev)->usb_device, 1);
+                                       libusb_claim_interface((*dev)->usb_device, 0);
+                                       goto out;
+                               }
+                               current_index++;
+                       }
+               }
        }
 
-       serialize_header(h, buffer);
-       ret = send_data(dev, buffer, AM7XXX_HEADER_WIRE_SIZE);
+       /* if we made it up to here we didn't find any device to open */
+       if (op == SCAN_OP_OPEN_DEVICE) {
+               error(ctx, "Cannot find any device to open\n");
+               ret = -ENODEV;
+               goto out;
+       }
+
+       /* everything went fine when building the device list */
+       ret = 0;
+out:
+       libusb_free_device_list(list, 1);
+       return ret;
+}
+
+int am7xxx_init(am7xxx_context **ctx)
+{
+       int ret = 0;
+
+       *ctx = malloc(sizeof(**ctx));
+       if (*ctx == NULL) {
+               fatal("cannot allocate the context (%s)\n", strerror(errno));
+               ret = -ENOMEM;
+               goto out;
+       }
+       memset(*ctx, 0, sizeof(**ctx));
+
+       /* Set the highest log level during initialization */
+       (*ctx)->log_level = AM7XXX_LOG_TRACE;
+
+       ret = libusb_init(&((*ctx)->usb_context));
        if (ret < 0)
-               fprintf(stderr, "send_header: failed to send data.\n");
+               goto out_free_context;
+
+       libusb_set_debug((*ctx)->usb_context, 3);
 
-       free(buffer);
+       ret = scan_devices(*ctx, SCAN_OP_BUILD_DEVLIST , 0, NULL);
+       if (ret < 0) {
+               error(*ctx, "scan_devices() failed\n");
+               am7xxx_shutdown(*ctx);
+               goto out;
+       }
+
+       /* Set a quieter log level as default for normal operation */
+       (*ctx)->log_level = AM7XXX_LOG_ERROR;
+       return 0;
+
+out_free_context:
+       free(*ctx);
+       *ctx = NULL;
+out:
        return ret;
 }
 
-am7xxx_device am7xxx_init(void)
+void am7xxx_shutdown(am7xxx_context *ctx)
 {
-       am7xxx_device dev;
+       am7xxx_device *current;
 
-       libusb_init(NULL);
-       libusb_set_debug(NULL, 3);
+       if (ctx == NULL) {
+               fatal("context must not be NULL!\n");
+               return;
+       }
 
-       dev = libusb_open_device_with_vid_pid(NULL,
-                                             AM7XXX_VENDOR_ID,
-                                             AM7XXX_PRODUCT_ID);
-       if (dev == NULL) {
-               errno = ENODEV;
-               perror("libusb_open_device_with_vid_pid");
-               goto out_libusb_exit;
+       current = ctx->devices_list;
+       while (current) {
+               am7xxx_device *next = current->next;
+               am7xxx_close_device(current);
+               free(current);
+               current = next;
        }
 
-       libusb_set_configuration(dev, 1);
-       libusb_claim_interface(dev, 0);
+       libusb_exit(ctx->usb_context);
+       free(ctx);
+       ctx = NULL;
+}
 
-       return dev;
+void am7xxx_set_log_level(am7xxx_context *ctx, am7xxx_log_level log_level)
+{
+       ctx->log_level = log_level;
+}
+
+int am7xxx_open_device(am7xxx_context *ctx, am7xxx_device **dev,
+                      unsigned int device_index)
+{
+       int ret;
+
+       if (ctx == NULL) {
+               fatal("context must not be NULL!\n");
+               return -EINVAL;
+       }
 
-out_libusb_exit:
-       libusb_exit(NULL);
-       return NULL;
+       ret = scan_devices(ctx, SCAN_OP_OPEN_DEVICE, device_index, dev);
+       if (ret < 0) {
+               errno = ENODEV;
+       } else if (ret > 0) {
+               warning(ctx, "device %d already open\n", device_index);
+               errno = EBUSY;
+               ret = -EBUSY;
+       }
+
+       return ret;
 }
 
-void am7xxx_shutdown(am7xxx_device dev)
+int am7xxx_close_device(am7xxx_device *dev)
 {
-       if (dev) {
-               libusb_close(dev);
-               libusb_exit(NULL);
+       if (dev == NULL) {
+               fatal("dev must not be NULL!\n");
+               return -EINVAL;
        }
+       if (dev->usb_device) {
+               libusb_release_interface(dev->usb_device, 0);
+               libusb_close(dev->usb_device);
+               dev->usb_device = NULL;
+       }
+       return 0;
 }
 
-int am7xxx_get_device_info(am7xxx_device dev,
-                          unsigned int *native_width,
-                          unsigned int *native_height,
-                          unsigned int *unknown0,
-                          unsigned int *unknown1)
+int am7xxx_get_device_info(am7xxx_device *dev,
+                          am7xxx_device_info *device_info)
 {
        int ret;
        struct am7xxx_header h = {
@@ -371,20 +681,85 @@ int am7xxx_get_device_info(am7xxx_device dev,
        if (ret < 0)
                return ret;
 
-       *native_width = h.header_data.devinfo.native_width;
-       *native_height = h.header_data.devinfo.native_height;
-       *unknown0 = h.header_data.devinfo.unknown0;
-       *unknown1 = h.header_data.devinfo.unknown1;
+       device_info->native_width = h.header_data.devinfo.native_width;
+       device_info->native_height = h.header_data.devinfo.native_height;
+#if 0
+       /* No reason to expose these in the public API until we know what they mean */
+       device_info->unknown0 = h.header_data.devinfo.unknown0;
+       device_info->unknown1 = h.header_data.devinfo.unknown1;
+#endif
 
        return 0;
 }
 
-int am7xxx_send_image(am7xxx_device dev,
+int am7xxx_calc_scaled_image_dimensions(am7xxx_device *dev,
+                                       unsigned int upscale,
+                                       unsigned int original_width,
+                                       unsigned int original_height,
+                                       unsigned int *scaled_width,
+                                       unsigned int *scaled_height)
+{
+
+       am7xxx_device_info device_info;
+       float width_ratio;
+       float height_ratio;
+       int ret;
+
+       ret = am7xxx_get_device_info(dev, &device_info);
+       if (ret < 0) {
+               error(dev->ctx, "cannot get device info\n");
+               return ret;
+       }
+
+       /*
+        * Check if we need to rescale; if the input image fits the native
+        * dimensions there is no need to, unless we want to upscale.
+        */
+       if (!upscale &&
+           original_width <= device_info.native_width &&
+           original_height <= device_info.native_height ) {
+               debug(dev->ctx, "CASE 0, no rescaling, the original image fits already\n");
+               *scaled_width = original_width;
+               *scaled_height = original_height;
+               return 0;
+       }
+
+       /* Input dimensions relative to the device native dimensions */
+       width_ratio =  (float)original_width / device_info.native_width;
+       height_ratio = (float)original_height / device_info.native_height;
+
+       if (width_ratio > height_ratio) {
+               /*
+                * The input is proportionally "wider" than the device viewport
+                * so its height needs to be adjusted
+                */
+               debug(dev->ctx, "CASE 1, original image wider, adjust the scaled height\n");
+               *scaled_width = device_info.native_width;
+               *scaled_height = (unsigned int)lroundf(original_height / width_ratio);
+       } else if (width_ratio < height_ratio) {
+               /*
+                * The input is proportionally "taller" than the device viewport
+                * so its width needs to be adjusted
+                */
+               debug(dev->ctx, "CASE 2 original image taller, adjust the scaled width\n");
+               *scaled_width = (unsigned int)lroundf(original_width / height_ratio);
+               *scaled_height = device_info.native_height;
+       } else {
+               debug(dev->ctx, "CASE 3, just rescale, same aspect ratio already\n");
+               *scaled_width = device_info.native_width;
+               *scaled_height = device_info.native_height;
+       }
+       debug(dev->ctx, "scaled dimensions: %dx%d\n", *scaled_width, *scaled_height);
+
+       return 0;
+}
+
+int am7xxx_send_image(am7xxx_device *dev,
                      am7xxx_image_format format,
                      unsigned int width,
                      unsigned int height,
                      uint8_t *image,
-                     unsigned int size)
+                     unsigned int image_size)
 {
        int ret;
        struct am7xxx_header h = {
@@ -398,7 +773,7 @@ int am7xxx_send_image(am7xxx_device dev,
                                .format     = format,
                                .width      = width,
                                .height     = height,
-                               .image_size = size,
+                               .image_size = image_size,
                        },
                },
        };
@@ -407,13 +782,15 @@ int am7xxx_send_image(am7xxx_device dev,
        if (ret < 0)
                return ret;
 
-       if (image == NULL || size == 0)
+       if (image == NULL || image_size == 0) {
+               warning(dev->ctx, "Not sending any data, check the 'image' or 'image_size' parameters\n");
                return 0;
+       }
 
-       return send_data(dev, image, size);
+       return send_data(dev, image, image_size);
 }
 
-int am7xxx_set_power_mode(am7xxx_device dev, am7xxx_power_mode mode)
+int am7xxx_set_power_mode(am7xxx_device *dev, am7xxx_power_mode mode)
 {
        int ret;
        struct am7xxx_header h = {
@@ -455,7 +832,7 @@ int am7xxx_set_power_mode(am7xxx_device dev, am7xxx_power_mode mode)
                break;
 
        default:
-               fprintf(stderr, "Unsupported power mode.\n");
+               error(dev->ctx, "Power mode not supported!\n");
                return -EINVAL;
        };
 
index e30057b..e67bcb6 100644 (file)
  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  */
 
+/**
+ * @file
+ * Public libam7xxx API.
+ */
+
 #ifndef __AM7XXX_H
 #define __AM7XXX_H
 
-#include <libusb-1.0/libusb.h>
-
 #ifdef __cplusplus
 extern "C" {
 #endif
 
-typedef libusb_device_handle *am7xxx_device;
 
+/**
+ * @typedef am7xxx_context
+ *
+ * An opaque data type representing a context.
+ */
+struct _am7xxx_context;
+typedef struct _am7xxx_context am7xxx_context;
+
+/** 
+ * @typedef am7xxx_device
+ *
+ * An opaque data type representing an am7xxx device.
+ */
+struct _am7xxx_device;
+typedef struct _am7xxx_device am7xxx_device;
+
+/**
+ * A struct describing device specific properties.
+ *
+ * A user program may want to inspect these before providing data to the
+ * device. For instance, when sending an image the user may want to rescale it
+ * to the device native width and height in order to be sure the image will be
+ * displayed in its entirety.
+ */
+typedef struct {
+       unsigned int native_width;  /**< The device native width. */
+       unsigned int native_height; /**< The device native height. */
+} am7xxx_device_info;
+
+/**
+ * The verbosity level of logging messages.
+ *
+ * This can be set with am7xxx_set_log_level() and the level will be used
+ * internally by libam7xxx to adjust the granularity of the information
+ * exposed to the user about the internal library operations.
+ */
+typedef enum {
+       AM7XXX_LOG_FATAL   = 0, /**< Fatal messages, the user application should stop if it gets one of this. */
+       AM7XXX_LOG_ERROR   = 1, /**< Error messages, typically they describe API functions failures. */
+       AM7XXX_LOG_WARNING = 2, /**< Warnings about conditions worth mentioning to the user. */
+       AM7XXX_LOG_INFO    = 3, /**< Informations about the device operations. */
+       AM7XXX_LOG_DEBUG   = 4, /**< Informations about the library internals. */
+       AM7XXX_LOG_TRACE   = 5, /**< Verbose informations about the communication with the hardware. */
+} am7xxx_log_level;
+
+/**
+ * The image formats accepted by the device.
+ */
 typedef enum {
-       AM7XXX_IMAGE_FORMAT_JPEG = 1,
-       AM7XXX_IMAGE_FORMAT_NV12 = 2,
+       AM7XXX_IMAGE_FORMAT_JPEG = 1, /**< JPEG format. */
+       AM7XXX_IMAGE_FORMAT_NV12 = 2, /**< Raw YUV in the NV12 variant. */
 } am7xxx_image_format;
 
+/**
+ * The device power modes.
+ *
+ * An am7xxx device can operate in several power modes. A certain power mode
+ * may have effect on the display brightness or on the device power
+ * consumption.
+ *             
+ * @note Most am7xxx devices come with a Y-shaped USB cable with a Master and
+ * a Slave connector, higher power modes may require that both connectors are
+ * plugged in to the host system for the device to work properly.
+ *
+ * @note At higher power modes some devices may use a fan to cool down the
+ * internal hardware components, and hence may be noisier in this case.
+ */
 typedef enum {
-       AM7XXX_POWER_OFF    = 0,
-       AM7XXX_POWER_LOW    = 1,
-       AM7XXX_POWER_MIDDLE = 2,
-       AM7XXX_POWER_HIGH   = 3,
-       AM7XXX_POWER_TURBO  = 4,
+       AM7XXX_POWER_OFF    = 0, /**< Display is powered off, no image shown. */
+       AM7XXX_POWER_LOW    = 1, /**< Low power consumption but also low brightness. */
+       AM7XXX_POWER_MIDDLE = 2, /**< Middle level of brightness. This and upper modes need both the Master and Slave USB connectors plugged. */
+       AM7XXX_POWER_HIGH   = 3, /**< More brightness, but more power consumption. */
+       AM7XXX_POWER_TURBO  = 4, /**< Max brightness and power consumption. */
 } am7xxx_power_mode;
 
-am7xxx_device am7xxx_init(void);
+/**
+ * Initialize the library context and data structures, and scan for devices.
+ *
+ * @param[out] ctx A pointer to the context the library will be used in.
+ *
+ * @return 0 on success, a negative value on error
+ */
+int am7xxx_init(am7xxx_context **ctx);
 
-void am7xxx_shutdown(am7xxx_device dev);
+/**
+ * Cleanup the library data structures and free the context.
+ *
+ * @param[in,out] ctx The context to free.
+ */
+void am7xxx_shutdown(am7xxx_context *ctx);
 
-int am7xxx_get_device_info(am7xxx_device dev,
-                          unsigned int *native_width,
-                          unsigned int *native_height,
-                          unsigned int *unknown0,
-                          unsigned int *unknown1);
+/**
+ * Set verbosity level of log messages.
+ *
+ * @note The level is per-context.
+ *
+ * @note Messages of level AM7XXX_LOG_FATAL are always shown, regardless
+ * of the value of the log_level parameter.
+ *
+ * @param[in] ctx The context to set the log level for
+ * @param[in] log_level The verbosity level to use in the context (see @link am7xxx_log_level @endlink)
+ */
+void am7xxx_set_log_level(am7xxx_context *ctx, am7xxx_log_level log_level);
+
+/**
+ * Open an am7xxx_device according to a index.
+ *
+ * The semantics of the 'device_index' argument follows the order
+ * of the devices as found when scanning the bus at am7xxx_init() time.
+ *
+ * @note When the user tries to open a device already opened the function
+ * returns -EBUSY and the device is left open.
+ *
+ * @param[in] ctx The context to open the device in
+ * @param[out] dev A pointer to the structure representing the device to open
+ * @param[in] device_index The index of the device on the bus
+ *
+ * @return 0 on success, a negative value on error
+ */
+int am7xxx_open_device(am7xxx_context *ctx,
+                      am7xxx_device **dev,
+                      unsigned int device_index);
 
-int am7xxx_send_image(am7xxx_device dev,
+/**
+ * Close an am7xxx_device.
+ *
+ * Close an am7xxx_device so that it becomes available for some other
+ * user/process to open it.
+ *
+ * @param[in] dev A pointer to the structure representing the device to close
+ *
+ * @return 0 on success, a negative value on error
+ */
+int am7xxx_close_device(am7xxx_device *dev);
+
+/**
+ * Get info about an am7xxx device.
+ *
+ * Get information about a device, in the form of a
+ * @link am7xxx_device_info @endlink structure.
+ *
+ * @param[in] dev A pointer to the structure representing the device to get info of
+ * @param[out] device_info A pointer to the structure where to store the device info (see @link am7xxx_device_info @endlink)
+ *
+ * @return 0 on success, a negative value on error
+ */
+int am7xxx_get_device_info(am7xxx_device *dev,
+                          am7xxx_device_info *device_info);
+
+/**
+ * Calculate the dimensions of an image to be shown on an am7xxx device.
+ *
+ * Before sending images bigger than the device native dimensions the user
+ * needs to rescale them, this utility function does the calculation in a way
+ * that the original image aspect ratio is preserved.
+ * 
+ * @param[in] dev A pointer to the structure representing the device to get info of
+ * @param[in] upscale Whether to calculate scaled dimensions for images smaller than the native dimensions
+ * @param[in] original_width The width of the original image
+ * @param[in] original_height The height of the original image
+ * @param[out] scaled_width The width the rescaled image should have
+ * @param[out] scaled_height The height the rescaled image should have
+ *
+ * @return 0 on success, a negative value on error
+ */
+int am7xxx_calc_scaled_image_dimensions(am7xxx_device *dev,
+                                       unsigned int upscale,
+                                       unsigned int original_width,
+                                       unsigned int original_height,
+                                       unsigned int *scaled_width,
+                                       unsigned int *scaled_height);
+/**
+ * Send an image for display on a am7xxx device.
+ *
+ * This is the function that actually makes the device display something.
+ * Static pictures can be sent just once and the device will keep showing them
+ * until another image get sent or some command resets or turns off the display.
+ *
+ * @param[in] dev A pointer to the structure representing the device to get info of
+ * @param[in] format The format the image is in (see @link am7xxx_image_format @endlink enum)
+ * @param[in] width The width of the image
+ * @param[in] height The height of the image
+ * @param[in] image A buffer holding data in the format specified by the format parameter
+ * @param[in] image_size The size in bytes of the image buffer
+ *
+ * @return 0 on success, a negative value on error
+ */
+int am7xxx_send_image(am7xxx_device *dev,
                      am7xxx_image_format format,
                      unsigned int width,
                      unsigned int height,
                      unsigned char *image,
-                     unsigned int size);
+                     unsigned int image_size);
 
-/*
- * NOTE: if we set the mode to AM7XXX_POWER_OFF we can't turn the
- * display on again by using only am7xxx_set_power_mode().
+/**
+ * Set the power mode of an am7xxx device.
+ *
+ * \note If we set the mode to AM7XXX_POWER_OFF we can't turn the
+ * display on again by using only am7xxx_set_power_mode(). This needs to be
+ * investigated, maybe some other command can reset the device.
+ *
+ * @param[in] dev A pointer to the structure representing the device to get info of
+ * @param[in] mode The power mode to put the device in (see @link am7xxx_power_mode @endlink enum)
+ *
+ * @return 0 on success, a negative value on error
  *
- * Remember to mention that when writing the API doc.
  */
-int am7xxx_set_power_mode(am7xxx_device dev, am7xxx_power_mode mode);
+int am7xxx_set_power_mode(am7xxx_device *dev, am7xxx_power_mode mode);
 
 #ifdef __cplusplus
 }
index 2ad2256..dff65c6 100644 (file)
@@ -5,7 +5,7 @@ includedir=${prefix}/include
 
 Name: @PROJECT_NAME@
 Description: @PROJECT_DESCRIPTION@
-Requires: libusb-1.0
+Requires.private: libusb-1.0
 Version: @PROJECT_APIVER@
 Libs: -L${libdir} -lam7xxx
 Cflags: -I${includedir}
diff --git a/src/picoproj.c b/src/picoproj.c
deleted file mode 100644 (file)
index f8eb5bc..0000000
+++ /dev/null
@@ -1,181 +0,0 @@
-/* picoproj - test program for libam7xxx
- *
- * Copyright (C) 2012  Antonio Ospite <ospite@studenti.unina.it>
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation, either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program.  If not, see <http://www.gnu.org/licenses/>.
- */
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <sys/mman.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <fcntl.h>
-#include <unistd.h>
-
-#include "am7xxx.h"
-
-static void usage(char *name)
-{
-       printf("usage: %s [OPTIONS]\n\n", name);
-       printf("OPTIONS:\n");
-       printf("\t-f <filename>\t\tthe image file to upload\n");
-       printf("\t-F <format>\t\tthe image format to use (default is JPEG).\n");
-       printf("\t\t\t\tSUPPORTED FORMATS:\n");
-       printf("\t\t\t\t\t1 - JPEG\n");
-       printf("\t\t\t\t\t2 - YUV - NV12\n");
-       printf("\t-W <image width>\tthe width of the image to upload\n");
-       printf("\t-H <image height>\tthe height of the image to upload\n");
-       printf("\t-h \t\t\tthis help message\n");
-}
-
-int main(int argc, char *argv[])
-{
-       int ret;
-       int exit_code = EXIT_SUCCESS;
-       int opt;
-
-       char filename[FILENAME_MAX] = {0};
-       int image_fd;
-       struct stat st;
-       am7xxx_device dev;
-       int format = AM7XXX_IMAGE_FORMAT_JPEG;
-       int width = 800;
-       int height = 480;
-       unsigned char *image;
-       unsigned int size;
-       unsigned int native_width;
-       unsigned int native_height;
-       unsigned int unknown0;
-       unsigned int unknown1;
-
-       while ((opt = getopt(argc, argv, "f:F:W:H:h")) != -1) {
-               switch (opt) {
-               case 'f':
-                       strncpy(filename, optarg, FILENAME_MAX);
-                       break;
-               case 'F':
-                       format = atoi(optarg);
-                       switch(format) {
-                       case AM7XXX_IMAGE_FORMAT_JPEG:
-                               fprintf(stdout, "JPEG format\n");
-                               break;
-                       case AM7XXX_IMAGE_FORMAT_NV12:
-                               fprintf(stdout, "NV12 format\n");
-                               break;
-                       default:
-                               fprintf(stderr, "Unsupported format\n");
-                               exit(EXIT_FAILURE);
-                       }
-                       break;
-               case 'W':
-                       width = atoi(optarg);
-                       if (width < 0) {
-                               fprintf(stderr, "Unsupported width\n");
-                               exit(EXIT_FAILURE);
-                       }
-                       break;
-               case 'H':
-                       height = atoi(optarg);
-                       if (height < 0) {
-                               fprintf(stderr, "Unsupported height\n");
-                               exit(EXIT_FAILURE);
-                       }
-                       break;
-               case 'h':
-                       usage(argv[0]);
-                       exit(EXIT_SUCCESS);
-                       break;
-               default: /* '?' */
-                       usage(argv[0]);
-                       exit(EXIT_FAILURE);
-               }
-       }
-
-       if (filename[0] == '\0') {
-               fprintf(stderr, "An image file MUST be specified.\n");
-               exit_code = EXIT_FAILURE;
-               goto out;
-       }
-
-       image_fd = open(filename, O_RDONLY);
-       if (image_fd < 0) {
-               perror("open");
-               exit_code = EXIT_FAILURE;
-               goto out;
-       }
-       if (fstat(image_fd, &st) < 0) {
-               perror("fstat");
-               exit_code = EXIT_FAILURE;
-               goto out_close_image_fd;
-       }
-       size = st.st_size;
-
-       image = mmap(NULL, st.st_size, PROT_READ, MAP_SHARED, image_fd, 0);
-       if (image == NULL) {
-               perror("mmap");
-               exit_code = EXIT_FAILURE;
-               goto out_close_image_fd;
-       }
-
-       dev = am7xxx_init();
-       if (dev == NULL) {
-               perror("am7xxx_init");
-               exit_code = EXIT_FAILURE;
-               goto out_munmap;
-       }
-
-       ret = am7xxx_get_device_info(dev, &native_width, &native_height, &unknown0, &unknown1);
-       if (ret < 0) {
-               perror("am7xxx_get_info");
-               exit_code = EXIT_FAILURE;
-               goto cleanup;
-       }
-       printf("Native resolution: %dx%d\n", native_width, native_height);
-       printf("Unknown0: %d\n", unknown0);
-       printf("Unknown1: %d\n", unknown1);
-
-       ret = am7xxx_set_power_mode(dev, AM7XXX_POWER_LOW);
-       if (ret < 0) {
-               perror("am7xxx_set_power_mode");
-               exit_code = EXIT_FAILURE;
-               goto cleanup;
-       }
-
-       ret = am7xxx_send_image(dev, format, width, height, image, size);
-       if (ret < 0) {
-               perror("am7xxx_send_image");
-               exit_code = EXIT_FAILURE;
-               goto cleanup;
-       }
-
-       exit_code = EXIT_SUCCESS;
-
-cleanup:
-       am7xxx_shutdown(dev);
-
-out_munmap:
-       ret = munmap(image, size);
-       if (ret < 0)
-               perror("munmap");
-
-out_close_image_fd:
-       ret = close(image_fd);
-       if (ret < 0)
-               perror("close");
-
-out:
-       exit(exit_code);
-}