Merge branch 'unstable' into rettichschnidi
authorReto Schneider <github@reto-schneider.ch>
Fri, 16 Mar 2012 19:46:29 +0000 (20:46 +0100)
committerReto Schneider <github@reto-schneider.ch>
Fri, 16 Mar 2012 19:46:29 +0000 (20:46 +0100)
13 files changed:
CMakeLists.txt
cmake_modules/FindFFmpeg.cmake [new file with mode: 0644]
cmake_modules/FindXCB.cmake [new file with mode: 0644]
cmake_modules/MaintenanceTools.cmake [new file with mode: 0644]
contrib/55-am7xxx.rules
doc/CMakeLists.txt
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/picoproj.c [deleted file]

index aee9581..aba2d43 100644 (file)
@@ -16,6 +16,8 @@ set(PROJECT_APIVER
 set(CMAKE_MODULE_PATH 
   ${CMAKE_MODULE_PATH} "${CMAKE_CURRENT_SOURCE_DIR}/cmake_modules/")
 
+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)
@@ -76,30 +78,7 @@ set(CMAKE_C_FLAGS_DEBUG "-g -DDEBUG=1 -Werror")
 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)
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)
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"
index 81a7c45..ce111b2 100644 (file)
@@ -8,4 +8,8 @@ if(DOXYGEN_FOUND)
     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)
diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt
new file mode 100644 (file)
index 0000000..c70d121
--- /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_LIBAVDEVICE_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..f7e069a
--- /dev/null
@@ -0,0 +1,748 @@
+/*
+ * 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/>.
+ */
+
+#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");
+               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!");
+               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!");
+               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!");
+               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!");
+               goto cleanup_output;
+       }
+
+       /* allocate output frame */
+       picture_scaled = avcodec_alloc_frame();
+       if (picture_scaled == NULL) {
+               fprintf(stderr, "cannot allocate the scaled picture!\n");
+               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");
+               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");
+               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 <input path>\t\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 \t\t\tquality of jpeg sent to the device, between 1 and 100\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 format = AM7XXX_IMAGE_FORMAT_JPEG;
+       am7xxx_context *ctx;
+       am7xxx_device *dev;
+
+       while ((opt = getopt(argc, argv, "f:i:o:s:uF:q:h")) != -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(format) {
+                       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 'h':
+                       usage(argv[0]);
+                       ret = 0;
+                       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;
+       }
+
+       ret = am7xxx_open_device(ctx, &dev, 0);
+       if (ret < 0) {
+               perror("am7xxx_open_device");
+               goto cleanup;
+       }
+
+       ret = am7xxx_set_power_mode(dev, AM7XXX_POWER_LOW);
+       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..c3b199c
--- /dev/null
@@ -0,0 +1,211 @@
+/* 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-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");
+}
+
+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 217b0f1..bec1d5c 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)
@@ -36,9 +35,3 @@ if(UNIX AND NOT APPLE)
   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 30e689f..67718db 100644 (file)
@@ -691,6 +691,68 @@ int am7xxx_get_device_info(am7xxx_device *dev,
        return 0;
 }
 
+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 it's 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)(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)(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,
index 4fe9b00..df305e5 100644 (file)
@@ -179,6 +179,28 @@ 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 dimesions
+ * @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.
@@ -187,9 +209,9 @@ int am7xxx_get_device_info(am7xxx_device *dev,
  *
  * @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] 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 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
diff --git a/src/picoproj.c b/src/picoproj.c
deleted file mode 100644 (file)
index c3b199c..0000000
+++ /dev/null
@@ -1,211 +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-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");
-}
-
-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);
-}