changeset 32393:98fda5253e80

Extract code to read a pnm file into a separate function.
author reimar
date Sun, 10 Oct 2010 11:20:57 +0000
parents 7fd2de8d6f32
children 914208d188b9
files libvo/gl_common.c
diffstat 1 files changed, 48 insertions(+), 24 deletions(-) [+]
line wrap: on
line diff
--- a/libvo/gl_common.c	Sun Oct 10 09:30:42 2010 +0000
+++ b/libvo/gl_common.c	Sun Oct 10 11:20:57 2010 +0000
@@ -576,6 +576,47 @@
 
 #define MAXDIM (16 * 1024)
 
+static uint8_t *read_pnm(FILE *f, int *width, int *height,
+                         int *bytes_per_pixel, int *maxval) {
+  uint8_t *data;
+  int type;
+  unsigned w, h, m, val, bpp;
+  *width = *height = *bytes_per_pixel = *maxval = 0;
+  ppm_skip(f);
+  if (fgetc(f) != 'P')
+    return NULL;
+  type = fgetc(f);
+  if (type != '5' && type != '6')
+    return NULL;
+  ppm_skip(f);
+  if (fscanf(f, "%u", &w) != 1)
+    return NULL;
+  ppm_skip(f);
+  if (fscanf(f, "%u", &h) != 1)
+    return NULL;
+  ppm_skip(f);
+  if (fscanf(f, "%u", &m) != 1)
+    return NULL;
+  val = fgetc(f);
+  if (!isspace(val))
+    return NULL;
+  if (w > MAXDIM || h > MAXDIM)
+    return NULL;
+  bpp = (m > 255) ? 2 : 1;
+  if (type == '6')
+    bpp *= 3;
+  data = malloc(w * h * bpp);
+  if (fread(data, w * bpp, h, f) != h) {
+    free(data);
+    return NULL;
+  }
+  *width  = w;
+  *height = h;
+  *bytes_per_pixel = bpp;
+  *maxval = m;
+  return data;
+}
+
 /**
  * \brief creates a texture from a PPM file
  * \param target texture taget, usually GL_TEXTURE_2D
@@ -590,36 +631,19 @@
  */
 int glCreatePPMTex(GLenum target, GLenum fmt, GLint filter,
                    FILE *f, int *width, int *height, int *maxval) {
-  unsigned w, h, m, val, bpp;
-  char *data;
+  int w, h, m, bpp;
   GLenum type;
-  ppm_skip(f);
-  if (fgetc(f) != 'P' || fgetc(f) != '6')
-    return 0;
-  ppm_skip(f);
-  if (fscanf(f, "%u", &w) != 1)
-    return 0;
-  ppm_skip(f);
-  if (fscanf(f, "%u", &h) != 1)
+  uint8_t *data = read_pnm(f, &w, &h, &bpp, &m);
+  if (!data || (bpp != 3 && bpp != 6)) {
+    free(data);
     return 0;
-  ppm_skip(f);
-  if (fscanf(f, "%u", &m) != 1)
-    return 0;
-  val = fgetc(f);
-  if (!isspace(val))
-    return 0;
-  if (w > MAXDIM || h > MAXDIM)
-    return 0;
-  bpp = (m > 255) ? 6 : 3;
-  data = malloc(w * h * bpp);
-  if (fread(data, w * bpp, h, f) != h)
-    return 0;
+  }
   if (!fmt) {
-    fmt = (m > 255) ? hqtexfmt : 3;
+    fmt = bpp == 6 ? hqtexfmt : 3;
     if (fmt == GL_FLOAT_RGB32_NV && target != GL_TEXTURE_RECTANGLE)
       fmt = GL_RGB16;
   }
-  type = m > 255 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_BYTE;
+  type = bpp == 6 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_BYTE;
   glCreateClearTex(target, fmt, GL_RGB, type, filter, w, h, 0);
   glUploadTex(target, GL_RGB, type,
               data, w * bpp, 0, 0, w, h, 0);