XFA: Upgrade to libtiff 4.0.6.

R=jun_fang@foxitsoftware.com, tsepez@chromium.org

Review URL: https://codereview.chromium.org/1563103002 .
diff --git a/core/src/fxcodec/codec/fx_codec_tiff.cpp b/core/src/fxcodec/codec/fx_codec_tiff.cpp
index cf7af8f..51a443b 100644
--- a/core/src/fxcodec/codec/fx_codec_tiff.cpp
+++ b/core/src/fxcodec/codec/fx_codec_tiff.cpp
@@ -9,7 +9,7 @@
 #include "codec_int.h"

 

 extern "C" {

-#include "third_party/tiff_v403/tiffiop.h"

+#include "third_party/libtiff/tiffiop.h"

 }

 

 void* IccLib_CreateTransform_sRGB(const unsigned char* pProfileData,

@@ -181,22 +181,10 @@
 int _TIFFmemcmp(const void* ptr1, const void* ptr2, tmsize_t size) {

   return FXSYS_memcmp(ptr1, ptr2, (size_t)size);

 }

-static void _tiff_warning_ext(thandle_t context,

-                              const char* module,

-                              const char* fmt,

-                              va_list ap) {

-  if (module != NULL) {

-  }

-}

-TIFFErrorHandlerExt _TIFFwarningHandlerExt = _tiff_warning_ext;

-static void _tiff_error_ext(thandle_t context,

-                            const char* module,

-                            const char* fmt,

-                            va_list ap) {

-  if (module != NULL) {

-  }

-}

-TIFFErrorHandlerExt _TIFFerrorHandlerExt = _tiff_error_ext;

+

+TIFFErrorHandler _TIFFwarningHandler = nullptr;

+TIFFErrorHandler _TIFFerrorHandler = nullptr;

+

 int TIFFCmyk2Rgb(thandle_t context,

                  uint8 c,

                  uint8 m,

diff --git a/third_party/BUILD.gn b/third_party/BUILD.gn
index 51481dd..ed8037b 100644
--- a/third_party/BUILD.gn
+++ b/third_party/BUILD.gn
@@ -305,42 +305,42 @@
       "//third_party/pdfium:pdfium_config",
     ]
     sources = [
-      "tiff_v403/tiffiop.h",
-      "tiff_v403/tif_aux.c",
-      "tiff_v403/tif_close.c",
-      "tiff_v403/tif_codec.c",
-      "tiff_v403/tif_color.c",
-      "tiff_v403/tif_compress.c",
-      "tiff_v403/tif_dir.c",
-      "tiff_v403/tif_dirinfo.c",
-      "tiff_v403/tif_dirread.c",
-      "tiff_v403/tif_dirwrite.c",
-      "tiff_v403/tif_dumpmode.c",
-      "tiff_v403/tif_error.c",
-      "tiff_v403/tif_extension.c",
-      "tiff_v403/tif_fax3.c",
-      "tiff_v403/tif_fax3sm.c",
-      "tiff_v403/tif_flush.c",
-      "tiff_v403/tif_getimage.c",
-      "tiff_v403/tif_jpeg.c",
-      "tiff_v403/tif_luv.c",
-      "tiff_v403/tif_lzw.c",
-      "tiff_v403/tif_next.c",
-      "tiff_v403/tif_ojpeg.c",
-      "tiff_v403/tif_open.c",
-      "tiff_v403/tif_packbits.c",
-      "tiff_v403/tif_pixarlog.c",
-      "tiff_v403/tif_predict.c",
-      "tiff_v403/tif_print.c",
-      "tiff_v403/tif_read.c",
-      "tiff_v403/tif_strip.c",
-      "tiff_v403/tif_swab.c",
-      "tiff_v403/tif_thunder.c",
-      "tiff_v403/tif_tile.c",
-      "tiff_v403/tif_version.c",
-      "tiff_v403/tif_warning.c",
-      "tiff_v403/tif_write.c",
-      "tiff_v403/tif_zip.c",
+      "libtiff/tiffiop.h",
+      "libtiff/tif_aux.c",
+      "libtiff/tif_close.c",
+      "libtiff/tif_codec.c",
+      "libtiff/tif_color.c",
+      "libtiff/tif_compress.c",
+      "libtiff/tif_dir.c",
+      "libtiff/tif_dirinfo.c",
+      "libtiff/tif_dirread.c",
+      "libtiff/tif_dirwrite.c",
+      "libtiff/tif_dumpmode.c",
+      "libtiff/tif_error.c",
+      "libtiff/tif_extension.c",
+      "libtiff/tif_fax3.c",
+      "libtiff/tif_fax3sm.c",
+      "libtiff/tif_flush.c",
+      "libtiff/tif_getimage.c",
+      "libtiff/tif_jpeg.c",
+      "libtiff/tif_luv.c",
+      "libtiff/tif_lzw.c",
+      "libtiff/tif_next.c",
+      "libtiff/tif_ojpeg.c",
+      "libtiff/tif_open.c",
+      "libtiff/tif_packbits.c",
+      "libtiff/tif_pixarlog.c",
+      "libtiff/tif_predict.c",
+      "libtiff/tif_print.c",
+      "libtiff/tif_read.c",
+      "libtiff/tif_strip.c",
+      "libtiff/tif_swab.c",
+      "libtiff/tif_thunder.c",
+      "libtiff/tif_tile.c",
+      "libtiff/tif_version.c",
+      "libtiff/tif_warning.c",
+      "libtiff/tif_write.c",
+      "libtiff/tif_zip.c",
     ]
   }
 }
diff --git a/third_party/libtiff/0000-build-config.patch b/third_party/libtiff/0000-build-config.patch
new file mode 100644
index 0000000..50af2db
--- /dev/null
+++ b/third_party/libtiff/0000-build-config.patch
@@ -0,0 +1,337 @@
+diff a/third_party/libtiff/tiffiop.h b/third_party/libtiff/tiffiop.h
+--- a/third_party/libtiff/tiffiop.h
++++ b/third_party/libtiff/tiffiop.h
+@@ -30,7 +30,7 @@
+  * ``Library-private'' definitions.
+  */
+ 
+-#include "tif_config.h"
++#include "tiffconf.h"
+ 
+ #ifdef HAVE_FCNTL_H
+ # include <fcntl.h>
+diff a/third_party/libtiff/tif_jpeg.c b/third_party/libtiff/tif_jpeg.c
+--- a/third_party/libtiff/tif_jpeg.c
++++ b/third_party/libtiff/tif_jpeg.c
+@@ -85,8 +85,16 @@
+ # define HAVE_BOOLEAN            /* prevent jmorecfg.h from redefining it */
+ #endif
+ 
+-#include "jpeglib.h"
+-#include "jerror.h"
++#if defined(USE_SYSTEM_LIBJPEG)
++#include <jerror.h>
++#include <jpeglib.h>
++#elif defined(USE_LIBJPEG_TURBO)
++#include "third_party/libjpeg_turbo/jerror.h"
++#include "third_party/libjpeg_turbo/jpeglib.h"
++#else
++#include "third_party/libjpeg/jerror.h"
++#include "third_party/libjpeg/jpeglib.h"
++#endif
+ 
+ /* 
+  * Do we want to do special processing suitable for when JSAMPLE is a
+diff a/third_party/libtiff/tif_ojpeg.c b/third_party/libtiff/tif_ojpeg.c
+--- a/third_party/libtiff/tif_ojpeg.c
++++ b/third_party/libtiff/tif_ojpeg.c
+@@ -214,8 +214,17 @@
+ # define HAVE_BOOLEAN            /* prevent jmorecfg.h from redefining it */
+ #endif
+ 
+-#include "jpeglib.h"
+-#include "jerror.h"
++#if defined(USE_SYSTEM_LIBJPEG)
++#include <jerror.h>
++#include <jpeglib.h>
++#elif defined(USE_LIBJPEG_TURBO)
++#include "third_party/libjpeg_turbo/jerror.h"
++#include "third_party/libjpeg_turbo/jpeglib.h"
++#else
++#include "third_party/libjpeg/jerror.h"
++#include "third_party/libjpeg/jpeglib.h"
++#endif
++
+ 
+ typedef struct jpeg_error_mgr jpeg_error_mgr;
+ typedef struct jpeg_common_struct jpeg_common_struct;
+diff a/third_party/libtiff/tif_pixarlog.c b/third_party/libtiff/tif_pixarlog.c
+--- a/third_party/libtiff/tif_pixarlog.c
++++ b/third_party/libtiff/tif_pixarlog.c
+@@ -90,7 +90,7 @@
+  */
+ 
+ #include "tif_predict.h"
+-#include "zlib.h"
++#include "../zlib_v128/zlib.h"
+ 
+ #include <stdio.h>
+ #include <stdlib.h>
+diff a/third_party/libtiff/tif_zip.c b/third_party/libtiff/tif_zip.c
+--- a/third_party/libtiff/tif_zip.c
++++ b/third_party/libtiff/tif_zip.c
+@@ -47,7 +47,7 @@
+  * last found at ftp://ftp.uu.net/pub/archiving/zip/zlib/zlib-0.99.tar.gz.
+  */
+ #include "tif_predict.h"
+-#include "zlib.h"
++#include "../zlib_v128/zlib.h"
+ 
+ #include <stdio.h>
+ 
+diff a/third_party/libtiff/tiffconf.h b/third_party/libtiff/tiffconf.h
+--- /dev/null
++++ b/third_party/libtiff/tiffconf.h
+@@ -0,0 +1,252 @@
++/* libtiff/tiffconf.h.  Generated by configure.  */
++/*
++  Configuration defines for installed libtiff.
++  This file maintained for backward compatibility. Do not use definitions
++  from this file in your programs.
++*/
++#ifndef _TIFFCONF_
++#define _TIFFCONF_
++
++#ifndef _FX_SYSTEM_H_
++# include "../../core/include/fxcrt/fx_system.h"
++#endif
++
++//NOTE: The tiff codec requires an ANSI C compiler environment for building and 
++//		presumes an ANSI C environment for use.
++
++/* Define to 1 if you have the <fcntl.h> header file. */
++/* Define to 1 if you have the <sys/types.h> header file. */
++#if _FX_OS_ == _FX_WIN32_MOBILE_
++# define O_RDONLY       0x0000  /* open for reading only */
++# define O_WRONLY       0x0001  /* open for writing only */
++# define O_RDWR         0x0002  /* open for reading and writing */
++# define O_CREAT        0x0100  /* create and open file */
++# define O_TRUNC        0x0200  /* open and truncate */
++#else
++# define HAVE_SYS_TYPES_H 1
++# define HAVE_FCNTL_H 1
++#endif
++
++/* Compatibility stuff. */
++
++/* Define to 1 if you have the <assert.h> header file. */
++#define HAVE_ASSERT_H 1
++
++/* Define as 0 or 1 according to the floating point format suported by the
++   machine */
++#define HAVE_IEEEFP 1
++
++/* Define to 1 if you have the <string.h> header file. */
++//#define HAVE_STRING_H 1
++//fx_system.h already include the string.h in ANSIC
++
++/* Define to 1 if you have the <search.h> header file. */
++/*#define HAVE_SEARCH_H 1 */
++
++/* The size of a `int', as computed by sizeof. */
++/* According typedef int	int32_t; in the fx_system.h*/
++#define SIZEOF_INT 4
++
++/* Sunliang.Liu 20110325. We should config the correct long size for tif 
++   fax4decode optimize in tif_fax3.c  -- Linux64 decode issue. 
++   TESTDOC: Bug #23661 - z1.tif. */
++#if _FX_CPU_ == _FX_WIN64_ || _FX_CPU_ == _FX_X64_ || _FX_CPU_ == _FX_IA64_
++/* The size of `unsigned long', as computed by sizeof. */
++#define SIZEOF_UNSIGNED_LONG 8
++#else
++#define SIZEOF_UNSIGNED_LONG 4
++#endif
++
++#define HAVE_SNPRINTF 1
++
++/* Signed 8-bit type */
++#define TIFF_INT8_T signed char
++
++/* Unsigned 8-bit type */
++#define TIFF_UINT8_T unsigned char
++
++/* Signed 16-bit type */
++#define TIFF_INT16_T signed short
++
++/* Unsigned 16-bit type */
++#define TIFF_UINT16_T unsigned short
++
++/* Signed 32-bit type */
++#define TIFF_INT32_T signed int
++
++/* Unsigned 32-bit type */
++#define TIFF_UINT32_T unsigned int
++
++/* Signed 32-bit type formatter */
++#define TIFF_INT32_FORMAT "%d"
++
++/* Unsigned 32-bit type formatter */
++#define TIFF_UINT32_FORMAT "%u"
++
++#ifdef _MSC_VER		// windows
++
++/* Signed 64-bit type formatter */
++#define TIFF_INT64_FORMAT "%I64d"
++
++/* Unsigned 64-bit type formatter */
++#define TIFF_UINT64_FORMAT "%I64u"
++
++/* Signed 64-bit type */
++#define TIFF_INT64_T signed __int64
++
++/* Unsigned 64-bit type */
++#define TIFF_UINT64_T unsigned __int64
++
++#else						// linux/unix
++
++#if 0 //_FX_CPU_ == _FX_X64_	// linux/unix 64
++
++/* Signed 64-bit type formatter */
++#define TIFF_INT64_FORMAT "%ld"
++
++/* Unsigned 64-bit type formatter */
++#define TIFF_UINT64_FORMAT "%lu"
++
++/* Signed 64-bit type */
++#define TIFF_INT64_T signed long
++
++#else						// linux/unix 32
++
++/* Signed 64-bit type formatter */
++#define TIFF_INT64_FORMAT "%lld"
++
++/* Unsigned 64-bit type formatter */
++#define TIFF_UINT64_FORMAT "%llu"
++
++/* Signed 64-bit type */
++#define TIFF_INT64_T signed long long
++
++#endif						// end _FX_CPU_
++
++/* Unsigned 64-bit type */
++#define TIFF_UINT64_T unsigned long long
++
++#endif
++
++
++/* Signed size type */
++#ifdef _MSC_VER
++
++#if defined(_WIN64)
++#define TIFF_SSIZE_T signed __int64
++#else
++#define TIFF_SSIZE_T signed int
++#endif
++
++#else
++
++#define TIFF_SSIZE_T signed long
++
++#endif
++
++/* Signed size type formatter */
++#if defined(_WIN64)
++#define TIFF_SSIZE_FORMAT "%I64d"
++#else
++#define TIFF_SSIZE_FORMAT "%ld"
++#endif
++
++/* Pointer difference type */
++#ifdef _MSC_VER
++#define TIFF_PTRDIFF_T long
++#else
++#define TIFF_PTRDIFF_T ptrdiff_t
++#endif
++
++/* Signed 64-bit type */
++/*#define TIFF_INT64_T signed __int64*/
++
++/* Unsigned 64-bit type */
++/*#define TIFF_UINT64_T unsigned __int64*/
++
++/* Define to `__inline__' or `__inline' if that's what the C compiler
++   calls it, or to nothing if 'inline' is not supported under any name.  */
++#ifndef __cplusplus
++# ifndef inline
++#  define inline __inline
++# endif
++#endif
++
++#define lfind _lfind
++
++#define BSDTYPES
++
++/* Set the native cpu bit order (FILLORDER_LSB2MSB or FILLORDER_MSB2LSB) */
++#define HOST_FILLORDER FILLORDER_LSB2MSB
++
++/* Native cpu byte order: 1 if big-endian (Motorola) or 0 if little-endian
++   (Intel) */
++#if _FX_ENDIAN_ == _FX_BIG_ENDIAN_
++# define HOST_BIGENDIAN 1
++#else
++# define HOST_BIGENDIAN 0
++#endif
++
++/* Support CCITT Group 3 & 4 algorithms */
++#define CCITT_SUPPORT 1
++
++/* Support JPEG compression (requires IJG JPEG library) */
++#define JPEG_SUPPORT 1
++
++/* Support LogLuv high dynamic range encoding */
++#define LOGLUV_SUPPORT 1
++
++/* Support LZW algorithm */
++#define LZW_SUPPORT 1
++
++/* Support NeXT 2-bit RLE algorithm */
++#define NEXT_SUPPORT 1
++
++/* Support Old JPEG compresson (read contrib/ojpeg/README first! Compilation
++   fails with unpatched IJG JPEG library) */
++#define  OJPEG_SUPPORT	1
++
++/* Support Macintosh PackBits algorithm */
++#define PACKBITS_SUPPORT 1
++
++/* Support Pixar log-format algorithm (requires Zlib) */
++#define PIXARLOG_SUPPORT 1
++
++/* Support ThunderScan 4-bit RLE algorithm */
++#define THUNDER_SUPPORT 1
++
++/* Support Deflate compression */
++#define ZIP_SUPPORT 1
++
++/* Support strip chopping (whether or not to convert single-strip uncompressed
++   images to mutiple strips of ~8Kb to reduce memory usage) */
++#define STRIPCHOP_DEFAULT TIFF_STRIPCHOP
++
++/* Enable SubIFD tag (330) support */
++#define SUBIFD_SUPPORT 1
++
++/* Treat extra sample as alpha (default enabled). The RGBA interface will
++   treat a fourth sample with no EXTRASAMPLE_ value as being ASSOCALPHA. Many
++   packages produce RGBA files but don't mark the alpha properly. */
++#define DEFAULT_EXTRASAMPLE_AS_ALPHA 1
++
++/* Pick up YCbCr subsampling info from the JPEG data stream to support files
++   lacking the tag (default enabled). */
++#define CHECK_JPEG_YCBCR_SUBSAMPLING 1
++
++/* Support MS MDI magic number files as TIFF */
++#define MDI_SUPPORT 1
++
++/*
++ * Feature support definitions.
++ * XXX: These macros are obsoleted. Don't use them in your apps!
++ * Macros stays here for backward compatibility and should be always defined.
++ */
++#define COLORIMETRY_SUPPORT
++#define YCBCR_SUPPORT
++#define CMYK_SUPPORT
++#define ICC_SUPPORT
++#define PHOTOSHOP_SUPPORT
++#define IPTC_SUPPORT
++
++#endif /* _TIFFCONF_ */
diff --git a/third_party/libtiff/README.pdfium b/third_party/libtiff/README.pdfium
new file mode 100644
index 0000000..bee4729
--- /dev/null
+++ b/third_party/libtiff/README.pdfium
@@ -0,0 +1,12 @@
+Name: LibTIFF
+URL: http://www.remotesensing.org/libtiff/
+Version: 4.0.6
+Security Critical: yes
+License: BSD
+
+Description:
+TIFF library.
+
+Local Modifications:
+
+0000-build-config.patch: Local build configuration changes.
diff --git a/third_party/tiff_v403/t4.h b/third_party/libtiff/t4.h
similarity index 100%
rename from third_party/tiff_v403/t4.h
rename to third_party/libtiff/t4.h
diff --git a/third_party/tiff_v403/tif_aux.c b/third_party/libtiff/tif_aux.c
similarity index 99%
rename from third_party/tiff_v403/tif_aux.c
rename to third_party/libtiff/tif_aux.c
index 7d71214..927150a 100644
--- a/third_party/tiff_v403/tif_aux.c
+++ b/third_party/libtiff/tif_aux.c
@@ -356,4 +356,3 @@
  * fill-column: 78
  * End:
  */
- 
\ No newline at end of file
diff --git a/third_party/tiff_v403/tif_close.c b/third_party/libtiff/tif_close.c
similarity index 99%
rename from third_party/tiff_v403/tif_close.c
rename to third_party/libtiff/tif_close.c
index 6181b97..13d2bab 100644
--- a/third_party/tiff_v403/tif_close.c
+++ b/third_party/libtiff/tif_close.c
@@ -138,4 +138,3 @@
  * fill-column: 78
  * End:
  */
-
diff --git a/third_party/tiff_v403/tif_codec.c b/third_party/libtiff/tif_codec.c
similarity index 96%
rename from third_party/tiff_v403/tif_codec.c
rename to third_party/libtiff/tif_codec.c
index 012a90b..7cb46f6 100644
--- a/third_party/tiff_v403/tif_codec.c
+++ b/third_party/libtiff/tif_codec.c
@@ -1,4 +1,4 @@
-/* $Id: tif_codec.c,v 1.15 2010-12-14 12:53:00 dron Exp $ */
+/* $Id: tif_codec.c,v 1.17 2015-08-19 02:31:04 bfriesen Exp $ */
 
 /*
  * Copyright (c) 1988-1997 Sam Leffler
@@ -108,7 +108,7 @@
 	const TIFFCodec* c = TIFFFindCODEC(tif->tif_dir.td_compression);
         char compression_code[20];
         
-        sprintf( compression_code, "%d", tif->tif_dir.td_compression );
+        sprintf(compression_code, "%d",tif->tif_dir.td_compression );
 	TIFFErrorExt(tif->tif_clientdata, tif->tif_name,
                      "%s compression support is not configured", 
                      c ? c->name : compression_code );
@@ -163,4 +163,3 @@
  * fill-column: 78
  * End:
  */
-
diff --git a/third_party/tiff_v403/tif_color.c b/third_party/libtiff/tif_color.c
similarity index 99%
rename from third_party/tiff_v403/tif_color.c
rename to third_party/libtiff/tif_color.c
index c55a4af..be4850c 100644
--- a/third_party/tiff_v403/tif_color.c
+++ b/third_party/libtiff/tif_color.c
@@ -35,6 +35,7 @@
  *
  * Color space conversion routines.
  */
+
 #include "tiffiop.h"
 #include <math.h>
 
@@ -284,4 +285,3 @@
  * fill-column: 78
  * End:
  */
-
diff --git a/third_party/tiff_v403/tif_compress.c b/third_party/libtiff/tif_compress.c
similarity index 99%
rename from third_party/tiff_v403/tif_compress.c
rename to third_party/libtiff/tif_compress.c
index 3a1e15f..20e72fd 100644
--- a/third_party/tiff_v403/tif_compress.c
+++ b/third_party/libtiff/tif_compress.c
@@ -302,4 +302,3 @@
  * fill-column: 78
  * End:
  */
-
diff --git a/third_party/tiff_v403/tif_dir.c b/third_party/libtiff/tif_dir.c
similarity index 95%
rename from third_party/tiff_v403/tif_dir.c
rename to third_party/libtiff/tif_dir.c
index 06951b4..73212c0 100644
--- a/third_party/tiff_v403/tif_dir.c
+++ b/third_party/libtiff/tif_dir.c
@@ -1,4 +1,4 @@
-/* $Id: tif_dir.c,v 1.113 2012-06-14 20:32:53 fwarmerdam Exp $ */
+/* $Id: tif_dir.c,v 1.121 2015-05-31 23:11:43 bfriesen Exp $ */
 
 /*
  * Copyright (c) 1988-1997 Sam Leffler
@@ -160,10 +160,12 @@
 	TIFFDirectory* td = &tif->tif_dir;
 	int status = 1;
 	uint32 v32, i, v;
+    double dblval;
 	char* s;
 	const TIFFField *fip = TIFFFindField(tif, tag, TIFF_ANY);
 	uint32 standard_tag = tag;
-
+	if( fip == NULL ) /* cannot happen since OkToChangeTag() already checks it */
+	    return 0;
 	/*
 	 * We want to force the custom code to be used for custom
 	 * fields even if the tag happens to match a well known 
@@ -283,10 +285,16 @@
 			setDoubleArrayOneValue(&td->td_smaxsamplevalue, va_arg(ap, double), td->td_samplesperpixel);
 		break;
 	case TIFFTAG_XRESOLUTION:
-		td->td_xresolution = (float) va_arg(ap, double);
+        dblval = va_arg(ap, double);
+        if( dblval < 0 )
+            goto badvaluedouble;
+		td->td_xresolution = (float) dblval;
 		break;
 	case TIFFTAG_YRESOLUTION:
-		td->td_yresolution = (float) va_arg(ap, double);
+        dblval = va_arg(ap, double);
+        if( dblval < 0 )
+            goto badvaluedouble;
+		td->td_yresolution = (float) dblval;
 		break;
 	case TIFFTAG_PLANARCONFIG:
 		v = (uint16) va_arg(ap, uint16_vap);
@@ -449,11 +457,11 @@
 		 * happens, for example, when tiffcp is used to convert between
 		 * compression schemes and codec-specific tags are blindly copied.
 		 */
-		if(fip == NULL || fip->field_bit != FIELD_CUSTOM) {
+		if(fip->field_bit != FIELD_CUSTOM) {
 			TIFFErrorExt(tif->tif_clientdata, module,
 			    "%s: Invalid %stag \"%s\" (not supported by codec)",
 			    tif->tif_name, isPseudoTag(tag) ? "pseudo-" : "",
-			    fip ? fip->field_name : "Unknown");
+			    fip->field_name);
 			status = 0;
 			break;
 		}
@@ -693,6 +701,16 @@
 		va_end(ap);
         }
 	return (0);
+badvaluedouble:
+        {
+        const TIFFField* fip=TIFFFieldWithTag(tif,tag);
+        TIFFErrorExt(tif->tif_clientdata, module,
+             "%s: Bad value %f for \"%s\" tag",
+             tif->tif_name, dblval,
+             fip ? fip->field_name : "Unknown");
+        va_end(ap);
+        }
+    return (0);
 }
 
 /*
@@ -809,6 +827,8 @@
 	int ret_val = 1;
 	uint32 standard_tag = tag;
 	const TIFFField* fip = TIFFFindField(tif, tag, TIFF_ANY);
+	if( fip == NULL ) /* cannot happen since TIFFGetField() already checks it */
+	    return 0;
 	
 	/*
 	 * We want to force the custom code to be used for custom
@@ -1006,14 +1026,14 @@
 				 * get a tag that is not valid for the image's
 				 * codec then we'll arrive here.
 				 */
-				if( fip == NULL || fip->field_bit != FIELD_CUSTOM )
+				if( fip->field_bit != FIELD_CUSTOM )
 				{
 					TIFFErrorExt(tif->tif_clientdata, "_TIFFVGetField",
 					    "%s: Invalid %stag \"%s\" "
 					    "(not supported by codec)",
 					    tif->tif_name,
 					    isPseudoTag(tag) ? "pseudo-" : "",
-					    fip ? fip->field_name : "Unknown");
+					    fip->field_name);
 					ret_val = 0;
 					break;
 				}
@@ -1302,8 +1322,20 @@
 	tif->tif_tagmethods.printdir = NULL;
 	/*
 	 *  Give client code a chance to install their own
-	 *  tag extensions & methods, prior to compression overloads.
+	 *  tag extensions & methods, prior to compression overloads,
+	 *  but do some prior cleanup first. (http://trac.osgeo.org/gdal/ticket/5054)
 	 */
+	if (tif->tif_nfieldscompat > 0) {
+		uint32 i;
+
+		for (i = 0; i < tif->tif_nfieldscompat; i++) {
+				if (tif->tif_fieldscompat[i].allocated_size)
+						_TIFFfree(tif->tif_fieldscompat[i].fields);
+		}
+		_TIFFfree(tif->tif_fieldscompat);
+		tif->tif_nfieldscompat = 0;
+		tif->tif_fieldscompat = NULL;
+	}
 	if (_TIFFextender)
 		(*_TIFFextender)(tif);
 	(void) TIFFSetField(tif, TIFFTAG_COMPRESSION, COMPRESSION_NONE);
@@ -1344,6 +1376,7 @@
 			if (((uint64)poffa!=poff)||(poffb<poffa)||(poffb<(tmsize_t)sizeof(uint16))||(poffb>tif->tif_size))
 			{
 				TIFFErrorExt(tif->tif_clientdata,module,"Error fetching directory count");
+                                  *nextdir=0;
 				return(0);
 			}
 			_TIFFmemcpy(&dircount,tif->tif_base+poffa,sizeof(uint16));
@@ -1453,7 +1486,8 @@
 				(void) TIFFSeekFile(tif,
 				    dircount16*20, SEEK_CUR);
 			if (!ReadOK(tif, nextdir, sizeof (uint64))) {
-				TIFFErrorExt(tif->tif_clientdata, module, "%s: Error fetching directory link",
+				TIFFErrorExt(tif->tif_clientdata, module,
+                                             "%s: Error fetching directory link",
 				    tif->tif_name);
 				return (0);
 			}
@@ -1470,6 +1504,7 @@
 uint16
 TIFFNumberOfDirectories(TIFF* tif)
 {
+	static const char module[] = "TIFFNumberOfDirectories";
 	uint64 nextdir;
 	uint16 n;
 	if (!(tif->tif_flags&TIFF_BIGTIFF))
@@ -1478,7 +1513,18 @@
 		nextdir = tif->tif_header.big.tiff_diroff;
 	n = 0;
 	while (nextdir != 0 && TIFFAdvanceDirectory(tif, &nextdir, NULL))
-		n++;
+        {
+                if (n != 65535) {
+                        ++n;
+                }
+		else
+                {
+                        TIFFErrorExt(tif->tif_clientdata, module,
+                                     "Directory count exceeded 65535 limit,"
+                                     " giving up on counting.");
+                        return (65535);
+                }
+        }
 	return (n);
 }
 
@@ -1657,4 +1703,3 @@
  * fill-column: 78
  * End:
  */
-
diff --git a/third_party/tiff_v403/tif_dir.h b/third_party/libtiff/tif_dir.h
similarity index 100%
rename from third_party/tiff_v403/tif_dir.h
rename to third_party/libtiff/tif_dir.h
diff --git a/third_party/tiff_v403/tif_dirinfo.c b/third_party/libtiff/tif_dirinfo.c
similarity index 95%
rename from third_party/tiff_v403/tif_dirinfo.c
rename to third_party/libtiff/tif_dirinfo.c
index 2914d40..7db4bdb 100644
--- a/third_party/tiff_v403/tif_dirinfo.c
+++ b/third_party/libtiff/tif_dirinfo.c
@@ -1,4 +1,4 @@
-/* $Id: tif_dirinfo.c,v 1.117 2012-08-19 16:56:34 bfriesen Exp $ */
+/* $Id: tif_dirinfo.c,v 1.121 2014-05-07 01:58:46 bfriesen Exp $ */
 
 /*
  * Copyright (c) 1988-1997 Sam Leffler
@@ -128,6 +128,8 @@
 	{ TIFFTAG_PIXAR_FOVCOT, 1, 1, TIFF_FLOAT, 0, TIFF_SETGET_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "FieldOfViewCotangent", NULL },
 	{ TIFFTAG_PIXAR_MATRIX_WORLDTOSCREEN, 16, 16, TIFF_FLOAT, 0, TIFF_SETGET_C0_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "MatrixWorldToScreen", NULL },
 	{ TIFFTAG_PIXAR_MATRIX_WORLDTOCAMERA, 16, 16, TIFF_FLOAT, 0, TIFF_SETGET_C0_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "MatrixWorldToCamera", NULL },
+	{ TIFFTAG_CFAREPEATPATTERNDIM, 2, 2, TIFF_SHORT, 0, TIFF_SETGET_C0_UINT16, TIFF_SETGET_UNDEFINED,	FIELD_CUSTOM, 0,	0,	"CFARepeatPatternDim", NULL },
+	{ TIFFTAG_CFAPATTERN,	4, 4,	TIFF_BYTE, 0, TIFF_SETGET_C0_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0,	0,	"CFAPattern" , NULL},
 	{ TIFFTAG_COPYRIGHT, -1, -1, TIFF_ASCII, 0, TIFF_SETGET_ASCII, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 1, 0, "Copyright", NULL },
 	/* end Pixar tags */
 	{ TIFFTAG_RICHTIFFIPTC, -3, -3, TIFF_LONG, 0, TIFF_SETGET_C32_UINT32, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "RichTIFFIPTC", NULL },
@@ -193,19 +195,19 @@
 	{ TIFFTAG_PERSAMPLE, 0, 0, TIFF_SHORT, 0, TIFF_SETGET_UNDEFINED, TIFF_SETGET_UNDEFINED, FIELD_PSEUDO, TRUE, FALSE, "PerSample", NULL},
 	/* end DNG tags */
 	/* begin TIFF/FX tags */
-    { TIFFTAG_INDEXED, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "Indexed" },
-    { TIFFTAG_GLOBALPARAMETERSIFD, 1, 1, TIFF_IFD, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "GlobalParametersIFD", NULL },
-    { TIFFTAG_PROFILETYPE, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "ProfileType", NULL },
-    { TIFFTAG_FAXPROFILE, 1, 1, TIFF_BYTE, 0, TIFF_SETGET_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "FaxProfile", NULL },
-    { TIFFTAG_CODINGMETHODS, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "CodingMethods", NULL },
-    { TIFFTAG_VERSIONYEAR, 4, 4, TIFF_BYTE, 0, TIFF_SETGET_C0_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "VersionYear", NULL },
-    { TIFFTAG_MODENUMBER, 1, 1, TIFF_BYTE, 0, TIFF_SETGET_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "ModeNumber", NULL },
-    { TIFFTAG_DECODE, -1, -1, TIFF_SRATIONAL, 0, TIFF_SETGET_C16_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "Decode", NULL },
-    { TIFFTAG_IMAGEBASECOLOR, -1, -1, TIFF_SHORT, 0, TIFF_SETGET_C16_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "ImageBaseColor", NULL },
-    { TIFFTAG_T82OPTIONS, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "T82Options", NULL },
-    { TIFFTAG_STRIPROWCOUNTS, -1, -1, TIFF_LONG, 0, TIFF_SETGET_C16_UINT32, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "StripRowCounts", NULL },
-    { TIFFTAG_IMAGELAYER, 2, 2, TIFF_LONG, 0, TIFF_SETGET_C0_UINT32, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "ImageLayer", NULL },
-	/* end DNG tags */
+        { TIFFTAG_INDEXED, 1, 1, TIFF_SHORT, 0, TIFF_SETGET_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "Indexed", NULL },
+        { TIFFTAG_GLOBALPARAMETERSIFD, 1, 1, TIFF_IFD8, 0, TIFF_SETGET_IFD8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "GlobalParametersIFD", NULL },
+        { TIFFTAG_PROFILETYPE, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "ProfileType", NULL },
+        { TIFFTAG_FAXPROFILE, 1, 1, TIFF_BYTE, 0, TIFF_SETGET_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "FaxProfile", NULL },
+        { TIFFTAG_CODINGMETHODS, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "CodingMethods", NULL },
+        { TIFFTAG_VERSIONYEAR, 4, 4, TIFF_BYTE, 0, TIFF_SETGET_C0_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "VersionYear", NULL },
+        { TIFFTAG_MODENUMBER, 1, 1, TIFF_BYTE, 0, TIFF_SETGET_UINT8, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "ModeNumber", NULL },
+        { TIFFTAG_DECODE, -1, -1, TIFF_SRATIONAL, 0, TIFF_SETGET_C16_FLOAT, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "Decode", NULL },
+        { TIFFTAG_IMAGEBASECOLOR, -1, -1, TIFF_SHORT, 0, TIFF_SETGET_C16_UINT16, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "ImageBaseColor", NULL },
+        { TIFFTAG_T82OPTIONS, 1, 1, TIFF_LONG, 0, TIFF_SETGET_UINT32, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "T82Options", NULL },
+        { TIFFTAG_STRIPROWCOUNTS, -1, -1, TIFF_LONG, 0, TIFF_SETGET_C16_UINT32, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 1, "StripRowCounts", NULL },
+        { TIFFTAG_IMAGELAYER, 2, 2, TIFF_LONG, 0, TIFF_SETGET_C0_UINT32, TIFF_SETGET_UNDEFINED, FIELD_CUSTOM, 0, 0, "ImageLayer", NULL },
+	/* end TIFF/FX tags */
 	/* begin pseudo tags */
 };
 
@@ -494,13 +496,6 @@
 	}
 }
 
-/* Sync from 3.8.2's modified*/
-#ifdef _WIN32_WCE
-void* wceex_bsearch(const void *key, const void *base, size_t nmemb, size_t size,
-						int (*compar)(const void *, const void *));
-#define bsearch wceex_bsearch
-#endif
-
 const TIFFField*
 TIFFFindField(TIFF* tif, uint32 tag, TIFFDataType dt)
 {
@@ -546,21 +541,10 @@
 	key.field_name = (char *)field_name;
 	key.field_type = dt;
 
-#if 1
 	ret = (const TIFFField **) 
             td_lfind(&pkey, tif->tif_fields, &tif->tif_nfields,
                      sizeof(TIFFField *), tagNameCompare);
-#else
-	// from old svn version
-	/*ret = (const TIFFFieldInfo **) lfind(&pkey,
-											tif->tif_fieldinfo, 
-											&tif->tif_nfields,
-											sizeof(TIFFFieldInfo *),
-											tagNameCompare);
-	*/
-	/*modify by Sunliang.Liu 20090827 for some platform not support lfind*/
-	ret = NULL;
-#endif
+
 	return tif->tif_foundfield = (ret ? *ret : NULL);
 }
 
@@ -729,7 +713,7 @@
 	 * note that this name is a special sign to TIFFClose() and
 	 * _TIFFSetupFields() to free the field
 	 */
-	sprintf(fld->field_name, "Tag %d", (int) tag);
+	snprintf(fld->field_name, 32, "Tag %d", (int) tag);
 
 	return fld;    
 }
@@ -973,4 +957,3 @@
  * fill-column: 78
  * End:
  */
-
diff --git a/third_party/tiff_v403/tif_dirread.c b/third_party/libtiff/tif_dirread.c
similarity index 98%
rename from third_party/tiff_v403/tif_dirread.c
rename to third_party/libtiff/tif_dirread.c
index b9e4ffa..a0dc68b 100644
--- a/third_party/tiff_v403/tif_dirread.c
+++ b/third_party/libtiff/tif_dirread.c
@@ -1,4 +1,4 @@
-/* $Id: tif_dirread.c,v 1.178 2012-08-19 16:56:34 bfriesen Exp $ */
+/* $Id: tif_dirread.c,v 1.191 2015-09-05 20:31:41 bfriesen Exp $ */
 
 /*
  * Copyright (c) 1988-1997 Sam Leffler
@@ -38,7 +38,7 @@
  *   the pointer to the appropriate TIFFField structure early on in
  *   TIFFReadDirectory, so as to eliminate current possibly repetitive lookup.
  */
- 
+
 #include "tiffiop.h"
 
 #define IGNORE 0          /* tag placeholder used below */
@@ -2172,11 +2172,6 @@
 			break;
 	}
 	_TIFFfree(origdata);
-	if (err!=TIFFReadDirEntryErrOk)
-	{
-		_TIFFfree(data);
-		return(err);
-	}
 	*value=data;
 	return(TIFFReadDirEntryErrOk);
 }
@@ -2414,11 +2409,6 @@
 			break;
 	}
 	_TIFFfree(origdata);
-	if (err!=TIFFReadDirEntryErrOk)
-	{
-		_TIFFfree(data);
-		return(err);
-	}
 	*value=data;
 	return(TIFFReadDirEntryErrOk);
 }
@@ -2657,11 +2647,6 @@
 			break;
 	}
 	_TIFFfree(origdata);
-	if (err!=TIFFReadDirEntryErrOk)
-	{
-		_TIFFfree(data);
-		return(err);
-	}
 	*value=data;
 	return(TIFFReadDirEntryErrOk);
 }
@@ -2723,11 +2708,6 @@
 			break;
 	}
 	_TIFFfree(origdata);
-	if (err!=TIFFReadDirEntryErrOk)
-	{
-		_TIFFfree(data);
-		return(err);
-	}
 	*value=data;
 	return(TIFFReadDirEntryErrOk);
 }
@@ -3194,11 +3174,7 @@
 /*
  * Largest 32-bit unsigned integer value.
  */
-#if defined(__WIN32__) && defined(_MSC_VER)
-# define TIFF_UINT32_MAX 0xFFFFFFFFI64
-#else
-# define TIFF_UINT32_MAX 0xFFFFFFFFLL
-#endif
+#define TIFF_UINT32_MAX 0xFFFFFFFFU
 
 static enum TIFFReadDirEntryErr
 TIFFReadDirEntryCheckRangeLongLong8(uint64 value)
@@ -3212,7 +3188,7 @@
 static enum TIFFReadDirEntryErr
 TIFFReadDirEntryCheckRangeLongSlong8(int64 value)
 {
-	if ((value<0) || (value > TIFF_UINT32_MAX))
+	if ((value < 0) || (value > (int64) TIFF_UINT32_MAX))
 		return(TIFFReadDirEntryErrRange);
 	else
 		return(TIFFReadDirEntryErrOk);
@@ -3229,19 +3205,21 @@
 		return(TIFFReadDirEntryErrOk);
 }
 
+/* Check that the 8-byte unsigned value can fit in a 4-byte unsigned range */
 static enum TIFFReadDirEntryErr
 TIFFReadDirEntryCheckRangeSlongLong8(uint64 value)
 {
-	if (value > 0x7FFFFFFFUL)
+	if (value > 0x7FFFFFFF)
 		return(TIFFReadDirEntryErrRange);
 	else
 		return(TIFFReadDirEntryErrOk);
 }
 
+/* Check that the 8-byte signed value can fit in a 4-byte signed range */
 static enum TIFFReadDirEntryErr
 TIFFReadDirEntryCheckRangeSlongSlong8(int64 value)
 {
-	if ((value < 0L-0x80000000L) || (value > 0x7FFFFFFFL))
+        if ((value < 0-((int64) 0x7FFFFFFF+1)) || (value > 0x7FFFFFFF))
 		return(TIFFReadDirEntryErrRange);
 	else
 		return(TIFFReadDirEntryErrOk);
@@ -3286,11 +3264,7 @@
 /*
  * Largest 64-bit signed integer value.
  */
-#if defined(__WIN32__) && defined(_MSC_VER)
-# define TIFF_INT64_MAX 0x7FFFFFFFFFFFFFFFI64
-#else
-# define TIFF_INT64_MAX 0x7FFFFFFFFFFFFFFFLL
-#endif
+#define TIFF_INT64_MAX ((int64)(((uint64) ~0) >> 1))
 
 static enum TIFFReadDirEntryErr
 TIFFReadDirEntryCheckRangeSlong8Long8(uint64 value)
@@ -3374,7 +3348,7 @@
 	} else {
 		switch (err) {
 			case TIFFReadDirEntryErrCount:
-				TIFFErrorExt(tif->tif_clientdata, module,
+				TIFFWarningExt(tif->tif_clientdata, module,
 				"Incorrect count for \"%s\"; tag ignored",
 					     tagname);
 				break;
@@ -3430,6 +3404,8 @@
 	const TIFFField* fip;
 	uint32 fii=FAILED_FII;
         toff_t nextdiroff;
+    int bitspersample_read = FALSE;
+
 	tif->tif_diroff=tif->tif_nextdiroff;
 	if (!TIFFCheckDirOffset(tif,tif->tif_nextdiroff))
 		return 0;           /* last offset or bad offset (IFD looping) */
@@ -3706,6 +3682,8 @@
 					}
 					if (!TIFFSetField(tif,dp->tdir_tag,value))
 						goto bad;
+                    if( dp->tdir_tag == TIFFTAG_BITSPERSAMPLE )
+                        bitspersample_read = TRUE;
 				}
 				break;
 			case TIFFTAG_SMINSAMPLEVALUE:
@@ -3763,6 +3741,19 @@
 					uint32 countrequired;
 					uint32 incrementpersample;
 					uint16* value=NULL;
+                    /* It would be dangerous to instanciate those tag values */
+                    /* since if td_bitspersample has not yet been read (due to */
+                    /* unordered tags), it could be read afterwards with a */
+                    /* values greater than the default one (1), which may cause */
+                    /* crashes in user code */
+                    if( !bitspersample_read )
+                    {
+                        fip = TIFFFieldWithTag(tif,dp->tdir_tag);
+                        TIFFWarningExt(tif->tif_clientdata,module,
+                                       "Ignoring %s since BitsPerSample tag not found",
+                                       fip ? fip->field_name : "unknown tagname");
+                        continue;
+                    }
 					countpersample=(1L<<tif->tif_dir.td_bitspersample);
 					if ((dp->tdir_tag==TIFFTAG_TRANSFERFUNCTION)&&(dp->tdir_count==(uint64)countpersample))
 					{
@@ -4278,7 +4269,8 @@
 	TIFFDirectory *td = &tif->tif_dir;
 	uint32 strip;
 
-    _TIFFFillStriles( tif );
+    if( !_TIFFFillStriles( tif ) )
+        return -1;
 
 	if (td->td_stripbytecount)
 		_TIFFfree(td->td_stripbytecount);
@@ -4377,6 +4369,11 @@
 
 	if (diroff == 0)			/* no more directories */
 		return 0;
+	if (tif->tif_dirnumber == 65535) {
+	    TIFFErrorExt(tif->tif_clientdata, "TIFFCheckDirOffset",
+			 "Cannot handle more than 65535 TIFF directories");
+	    return 0;
+	}
 
 	for (n = 0; n < tif->tif_dirnumber && tif->tif_dirlist; n++) {
 		if (tif->tif_dirlist[n] == diroff)
@@ -4396,7 +4393,10 @@
 		    tif->tif_dirnumber, 2 * sizeof(uint64), "for IFD list");
 		if (!new_dirlist)
 			return 0;
-		tif->tif_dirlistsize = 2 * tif->tif_dirnumber;
+		if( tif->tif_dirnumber >= 32768 )
+		    tif->tif_dirlistsize = 65535;
+		else
+		    tif->tif_dirlistsize = 2 * tif->tif_dirnumber;
 		tif->tif_dirlist = new_dirlist;
 	}
 
@@ -4708,6 +4708,7 @@
             return 0;
         }
 	fip=tif->tif_fields[fii];
+	assert(fip != NULL); /* should not happen */
 	assert(fip->set_field_type!=TIFF_SETGET_OTHER);  /* if so, we shouldn't arrive here but deal with this in specialized code */
 	assert(fip->set_field_type!=TIFF_SETGET_INT);    /* if so, we shouldn't arrive here as this is only the case for pseudo-tags */
 	err=TIFFReadDirEntryErrOk;
@@ -5355,7 +5356,7 @@
 	}
 	if (err!=TIFFReadDirEntryErrOk)
 	{
-		TIFFReadDirEntryOutputErr(tif,err,module,fip ? fip->field_name : "unknown tagname",recover);
+		TIFFReadDirEntryOutputErr(tif,err,module,fip->field_name,recover);
 		return(0);
 	}
 	return(1);
@@ -5611,4 +5612,3 @@
  * fill-column: 78
  * End:
  */
- 
diff --git a/third_party/tiff_v403/tif_dirwrite.c b/third_party/libtiff/tif_dirwrite.c
similarity index 99%
rename from third_party/tiff_v403/tif_dirwrite.c
rename to third_party/libtiff/tif_dirwrite.c
index fa20609..a0fd8dc 100644
--- a/third_party/tiff_v403/tif_dirwrite.c
+++ b/third_party/libtiff/tif_dirwrite.c
@@ -1,4 +1,4 @@
-/* $Id: tif_dirwrite.c,v 1.77 2012-07-06 19:18:31 bfriesen Exp $ */
+/* $Id: tif_dirwrite.c,v 1.78 2015-05-31 00:38:46 bfriesen Exp $ */
 
 /*
  * Copyright (c) 1988-1997 Sam Leffler
@@ -2839,14 +2839,15 @@
                          "Error writing directory link");
             return (0);
         }
-        
-        _TIFFfree( buf_to_write );
     }
     else
     {
         memcpy( &entry_offset, buf_to_write, count*TIFFDataWidth(datatype));
     }
 
+    _TIFFfree( buf_to_write );
+    buf_to_write = 0;
+
 /* -------------------------------------------------------------------- */
 /*      Adjust the directory entry.                                     */
 /* -------------------------------------------------------------------- */
diff --git a/third_party/tiff_v403/tif_dumpmode.c b/third_party/libtiff/tif_dumpmode.c
similarity index 99%
rename from third_party/tiff_v403/tif_dumpmode.c
rename to third_party/libtiff/tif_dumpmode.c
index 8f582e7..a94cf0b 100644
--- a/third_party/tiff_v403/tif_dumpmode.c
+++ b/third_party/libtiff/tif_dumpmode.c
@@ -141,4 +141,3 @@
  * fill-column: 78
  * End:
  */
-
diff --git a/third_party/tiff_v403/tif_error.c b/third_party/libtiff/tif_error.c
similarity index 92%
rename from third_party/tiff_v403/tif_error.c
rename to third_party/libtiff/tif_error.c
index 8c0ef6c..0bc8b87 100644
--- a/third_party/tiff_v403/tif_error.c
+++ b/third_party/libtiff/tif_error.c
@@ -29,9 +29,7 @@
  */
 #include "tiffiop.h"
 
-/*TIFFErrorHandlerExt _TIFFerrorHandlerExt = NULL;*/
-/* Modify here for use _TIFFerrorHandlerExt by Sunliang.Liu 20090715 */
-TIFFErrorHandler _TIFFerrorHandler = NULL;
+TIFFErrorHandlerExt _TIFFerrorHandlerExt = NULL;
 
 TIFFErrorHandler
 TIFFSetErrorHandler(TIFFErrorHandler handler)
@@ -80,4 +78,3 @@
  * fill-column: 78
  * End:
  */
-
diff --git a/third_party/tiff_v403/tif_extension.c b/third_party/libtiff/tif_extension.c
similarity index 99%
rename from third_party/tiff_v403/tif_extension.c
rename to third_party/libtiff/tif_extension.c
index 32d10cb..10afd41 100644
--- a/third_party/tiff_v403/tif_extension.c
+++ b/third_party/libtiff/tif_extension.c
@@ -30,6 +30,7 @@
  * Various routines support external extension of the tag set, and other
  * application extension capabilities. 
  */
+
 #include "tiffiop.h"
 
 int TIFFGetTagListCount( TIFF *tif )
@@ -115,4 +116,3 @@
  * fill-column: 78
  * End:
  */
-
diff --git a/third_party/tiff_v403/tif_fax3.c b/third_party/libtiff/tif_fax3.c
similarity index 97%
rename from third_party/tiff_v403/tif_fax3.c
rename to third_party/libtiff/tif_fax3.c
index 7ec8faa..bbe7255 100644
--- a/third_party/tiff_v403/tif_fax3.c
+++ b/third_party/libtiff/tif_fax3.c
@@ -1,4 +1,4 @@
-/* $Id: tif_fax3.c,v 1.74 2012-06-21 02:01:31 fwarmerdam Exp $ */
+/* $Id: tif_fax3.c,v 1.75 2015-08-30 20:49:55 erouault Exp $ */
 
 /*
  * Copyright (c) 1990-1997 Sam Leffler
@@ -23,6 +23,7 @@
  * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE 
  * OF THIS SOFTWARE.
  */
+
 #include "tiffiop.h"
 #ifdef CCITT_SUPPORT
 /*
@@ -369,7 +370,7 @@
 	static const unsigned char _fillmasks[] =
 	    { 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff };
 	unsigned char* cp;
-	uint32 x, bx, run,bx_;/* add bx_ = 8-bx for avoid ms evc compiler bug*/
+	uint32 x, bx, run;
 	int32 n, nw;
 	long* lp;
 
@@ -383,18 +384,10 @@
 	    if (run) {
 		cp = buf + (x>>3);
 		bx = x&7;
-// 		if (run > 8-bx) {
-// 			if (bx) {			/* align to byte boundary */
-// 				*cp++ &= 0xff << (8-bx);
-// 				run -= 8-bx;
-// 		    }
-//Modify by Sunliang.Liu 20090804
-//Detail: For avoid ms evc compiler bug in WCE ARMV4(I) Release
-		bx_ = 8-bx;
-		if (run > bx_) {
+		if (run > 8-bx) {
 		    if (bx) {			/* align to byte boundary */
-			*cp++ &= 0xff << bx_;
-			run -= bx_;
+			*cp++ &= 0xff << (8-bx);
+			run -= 8-bx;
 		    }
 		    if( (n = run >> 3) != 0 ) {	/* multiple bytes to fill */
 			if ((n/sizeof (long)) > 1) {
@@ -411,9 +404,6 @@
 			    } while (--nw);
 			    cp = (unsigned char*) lp;
 			}
-#ifdef FAX3_DEBUG
-			printf("_TIFFFax3fillruns ZERO: %d\n",n);
-#endif
 			ZERO(n, cp);
 			run &= 7;
 		    }
@@ -449,14 +439,12 @@
 			    } while (--nw);
 			    cp = (unsigned char*) lp;
 			}
-#ifdef FAX3_DEBUG
-			printf("_TIFFFax3fillruns FILL: %d\n",n);
-#endif
 			FILL(n, cp);
 			run &= 7;
 		    }
+                    /* Explicit 0xff masking to make icc -check=conversions happy */
 		    if (run)
-			cp[0] |= 0xff00 >> run;
+			cp[0] = (unsigned char)((cp[0] | (0xff00 >> run))&0xff);
 		} else
 		    cp[0] |= _fillmasks[run]>>bx;
 		x += runs[1];
@@ -1393,11 +1381,7 @@
 static int
 Fax4Decode(TIFF* tif, uint8* buf, tmsize_t occ, uint16 s)
 {
-#ifdef FAX3_DEBUG
-	FILE* file;
-#endif
 	DECLARE_STATE_2D(tif, sp, "Fax4Decode");
-
 	(void) s;
 	if (occ % sp->b.rowbytes)
 	{
@@ -1420,11 +1404,6 @@
                 if (EOLcnt)
                     goto EOFG4;
 		(*sp->fill)(buf, thisrun, pa, lastx);
-#ifdef FAX3_DEBUG
-		file = fopen("fillbuf.txt", "a");
-		fwrite(buf, sp->b.rowbytes, 1, file);
-		fclose(file);
-#endif
 		SETVALUE(0);		/* imaginary change for reference */
 		SWAP(uint32*, sp->curruns, sp->refruns);
 		buf += sp->b.rowbytes;
@@ -1440,11 +1419,6 @@
 #endif                
                 ClrBits( 13 );
 		(*sp->fill)(buf, thisrun, pa, lastx);
-#ifdef FAX3_DEBUG
-		file = fopen("fillbuf.txt", "a");
-		fwrite(buf, sp->b.rowbytes, 1, file);
-		fclose(file);
-#endif
 		UNCACHE_STATE(tif, sp);
 		return ( sp->line ? 1 : -1);	/* don't error on badly-terminated strips */
 	}
@@ -1620,4 +1594,3 @@
  * fill-column: 78
  * End:
  */
-
diff --git a/third_party/tiff_v403/tif_fax3.h b/third_party/libtiff/tif_fax3.h
similarity index 100%
rename from third_party/tiff_v403/tif_fax3.h
rename to third_party/libtiff/tif_fax3.h
diff --git a/third_party/tiff_v403/tif_fax3sm.c b/third_party/libtiff/tif_fax3sm.c
similarity index 99%
rename from third_party/tiff_v403/tif_fax3sm.c
rename to third_party/libtiff/tif_fax3sm.c
index c943f3e..822191e 100644
--- a/third_party/tiff_v403/tif_fax3sm.c
+++ b/third_party/libtiff/tif_fax3sm.c
@@ -1258,4 +1258,3 @@
  * fill-column: 78
  * End:
  */
-
diff --git a/third_party/tiff_v403/tif_flush.c b/third_party/libtiff/tif_flush.c
similarity index 99%
rename from third_party/tiff_v403/tif_flush.c
rename to third_party/libtiff/tif_flush.c
index 976cbc4..fd14e4c 100644
--- a/third_party/tiff_v403/tif_flush.c
+++ b/third_party/libtiff/tif_flush.c
@@ -116,4 +116,3 @@
  * fill-column: 78
  * End:
  */
-
diff --git a/third_party/tiff_v403/tif_getimage.c b/third_party/libtiff/tif_getimage.c
similarity index 93%
rename from third_party/tiff_v403/tif_getimage.c
rename to third_party/libtiff/tif_getimage.c
index 35c4786..f49b73f 100644
--- a/third_party/tiff_v403/tif_getimage.c
+++ b/third_party/libtiff/tif_getimage.c
@@ -1,4 +1,4 @@
-/* $Id: tif_getimage.c,v 1.82 2012-06-06 00:17:49 fwarmerdam Exp $ */
+/* $Id: tif_getimage.c,v 1.90 2015-06-17 01:34:08 bfriesen Exp $ */
 
 /*
  * Copyright (c) 1991-1997 Sam Leffler
@@ -182,8 +182,23 @@
 				    "Planarconfiguration", td->td_planarconfig);
 				return (0);
 			}
+			if( td->td_samplesperpixel != 3 )
+            {
+                sprintf(emsg,
+                        "Sorry, can not handle image with %s=%d",
+                        "Samples/pixel", td->td_samplesperpixel);
+                return 0;
+            }
 			break;
 		case PHOTOMETRIC_CIELAB:
+            if( td->td_samplesperpixel != 3 || td->td_bitspersample != 8 )
+            {
+                sprintf(emsg,
+                        "Sorry, can not handle image with %s=%d and %s=%d",
+                        "Samples/pixel", td->td_samplesperpixel,
+                        "Bits/sample", td->td_bitspersample);
+                return 0;
+            }
 			break;
 		default:
 			sprintf(emsg, "Sorry, can not handle image with %s=%d",
@@ -597,6 +612,10 @@
     int32 fromskew, toskew;
     uint32 nrow;
     int ret = 1, flip;
+    uint32 this_tw, tocol;
+    int32 this_toskew, leftmost_toskew;
+    int32 leftmost_fromskew;
+    uint32 leftmost_tw;
 
     buf = (unsigned char*) _TIFFmalloc(TIFFTileSize(tif));
     if (buf == 0) {
@@ -617,37 +636,50 @@
 	    toskew = -(int32)(tw - w);
     }
      
+    /*
+     *	Leftmost tile is clipped on left side if col_offset > 0.
+     */
+    leftmost_fromskew = img->col_offset % tw;
+    leftmost_tw = tw - leftmost_fromskew;
+    leftmost_toskew = toskew + leftmost_fromskew;
     for (row = 0; row < h; row += nrow)
     {
         rowstoread = th - (row + img->row_offset) % th;
     	nrow = (row + rowstoread > h ? h - row : rowstoread);
-	for (col = 0; col < w; col += tw) 
+	fromskew = leftmost_fromskew;
+	this_tw = leftmost_tw;
+	this_toskew = leftmost_toskew;
+	tocol = 0;
+	col = img->col_offset;
+	while (tocol < w)
         {
-	    if (TIFFReadTile(tif, buf, col+img->col_offset,  
+	    if (TIFFReadTile(tif, buf, col,  
 			     row+img->row_offset, 0, 0)==(tmsize_t)(-1) && img->stoponerr)
             {
                 ret = 0;
                 break;
             }
-	    
-	    pos = ((row+img->row_offset) % th) * TIFFTileRowSize(tif);  
-
-    	    if (col + tw > w) 
-            {
-                /*
-                 * Tile is clipped horizontally.  Calculate
-                 * visible portion and skewing factors.
-                 */
-                uint32 npix = w - col;
-                fromskew = tw - npix;
-                (*put)(img, raster+y*w+col, col, y,
-                       npix, nrow, fromskew, toskew + fromskew, buf + pos);
-            }
-            else 
-            {
-                (*put)(img, raster+y*w+col, col, y, tw, nrow, 0, toskew, buf + pos);
-            }
-        }
+            pos = ((row+img->row_offset) % th) * TIFFTileRowSize(tif) + \
+		   ((tmsize_t) fromskew * img->samplesperpixel);
+	    if (tocol + this_tw > w) 
+	    {
+		/*
+		 * Rightmost tile is clipped on right side.
+		 */
+		fromskew = tw - (w - tocol);
+		this_tw = tw - fromskew;
+		this_toskew = toskew + fromskew;
+	    }
+	    (*put)(img, raster+y*w+tocol, tocol, y, this_tw, nrow, fromskew, this_toskew, buf + pos);
+	    tocol += this_tw;
+	    col += this_tw;
+	    /*
+	     * After the leftmost tile, tiles are no longer clipped on left side.
+	     */
+	    fromskew = 0;
+	    this_tw = tw;
+	    this_toskew = toskew;
+	}
 
         y += (flip & FLIP_VERTICALLY ? -(int32) nrow : (int32) nrow);
     }
@@ -698,6 +730,10 @@
 	uint32 nrow;
 	int ret = 1, flip;
         int colorchannels;
+	uint32 this_tw, tocol;
+	int32 this_toskew, leftmost_toskew;
+	int32 leftmost_fromskew;
+	uint32 leftmost_tw;
 
 	tilesize = TIFFTileSize(tif);  
 	bufsize = TIFFSafeMultiply(tmsize_t,alpha?4:3,tilesize);
@@ -742,20 +778,31 @@
             break;
         }
 
+	/*
+	 *	Leftmost tile is clipped on left side if col_offset > 0.
+	 */
+	leftmost_fromskew = img->col_offset % tw;
+	leftmost_tw = tw - leftmost_fromskew;
+	leftmost_toskew = toskew + leftmost_fromskew;
 	for (row = 0; row < h; row += nrow)
 	{
 		rowstoread = th - (row + img->row_offset) % th;
 		nrow = (row + rowstoread > h ? h - row : rowstoread);
-		for (col = 0; col < w; col += tw)
+		fromskew = leftmost_fromskew;
+		this_tw = leftmost_tw;
+		this_toskew = leftmost_toskew;
+		tocol = 0;
+		col = img->col_offset;
+		while (tocol < w)
 		{
-			if (TIFFReadTile(tif, p0, col+img->col_offset,  
+			if (TIFFReadTile(tif, p0, col,  
 			    row+img->row_offset,0,0)==(tmsize_t)(-1) && img->stoponerr)
 			{
 				ret = 0;
 				break;
 			}
 			if (colorchannels > 1 
-                            && TIFFReadTile(tif, p1, col+img->col_offset,  
+                            && TIFFReadTile(tif, p1, col,  
                                             row+img->row_offset,0,1) == (tmsize_t)(-1) 
                             && img->stoponerr)
 			{
@@ -763,7 +810,7 @@
 				break;
 			}
 			if (colorchannels > 1 
-                            && TIFFReadTile(tif, p2, col+img->col_offset,  
+                            && TIFFReadTile(tif, p2, col,  
                                             row+img->row_offset,0,2) == (tmsize_t)(-1) 
                             && img->stoponerr)
 			{
@@ -771,7 +818,7 @@
 				break;
 			}
 			if (alpha
-                            && TIFFReadTile(tif,pa,col+img->col_offset,  
+                            && TIFFReadTile(tif,pa,col,  
                                             row+img->row_offset,0,colorchannels) == (tmsize_t)(-1) 
                             && img->stoponerr)
                         {
@@ -779,23 +826,27 @@
                             break;
 			}
 
-			pos = ((row+img->row_offset) % th) * TIFFTileRowSize(tif);  
-
-			if (col + tw > w)
+			pos = ((row+img->row_offset) % th) * TIFFTileRowSize(tif) + \
+			   ((tmsize_t) fromskew * img->samplesperpixel);
+			if (tocol + this_tw > w) 
 			{
 				/*
-				 * Tile is clipped horizontally.  Calculate
-				 * visible portion and skewing factors.
+				 * Rightmost tile is clipped on right side.
 				 */
-				uint32 npix = w - col;
-				fromskew = tw - npix;
-				(*put)(img, raster+y*w+col, col, y,
-				    npix, nrow, fromskew, toskew + fromskew,
-				    p0 + pos, p1 + pos, p2 + pos, (alpha?(pa+pos):NULL));
-			} else {
-				(*put)(img, raster+y*w+col, col, y,
-				    tw, nrow, 0, toskew, p0 + pos, p1 + pos, p2 + pos, (alpha?(pa+pos):NULL));
+				fromskew = tw - (w - tocol);
+				this_tw = tw - fromskew;
+				this_toskew = toskew + fromskew;
 			}
+			(*put)(img, raster+y*w+tocol, tocol, y, this_tw, nrow, fromskew, this_toskew, \
+				p0 + pos, p1 + pos, p2 + pos, (alpha?(pa+pos):NULL));
+			tocol += this_tw;
+			col += this_tw;
+			/*
+			* After the leftmost tile, tiles are no longer clipped on left side.
+			*/
+			fromskew = 0;
+			this_tw = tw;
+			this_toskew = toskew;
 		}
 
 		y += (flip & FLIP_VERTICALLY ?-(int32) nrow : (int32) nrow);
@@ -842,6 +893,12 @@
 	int32 fromskew, toskew;
 	int ret = 1, flip;
 
+	TIFFGetFieldDefaulted(tif, TIFFTAG_YCBCRSUBSAMPLING, &subsamplinghor, &subsamplingver);
+	if( subsamplingver == 0 ) {
+		TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif), "Invalid vertical YCbCr subsampling");
+		return (0);
+	}
+
 	buf = (unsigned char*) _TIFFmalloc(TIFFStripSize(tif));
 	if (buf == 0) {
 		TIFFErrorExt(tif->tif_clientdata, TIFFFileName(tif), "No space for strip buffer");
@@ -859,7 +916,7 @@
 	}
 
 	TIFFGetFieldDefaulted(tif, TIFFTAG_ROWSPERSTRIP, &rowsperstrip);
-	TIFFGetFieldDefaulted(tif, TIFFTAG_YCBCRSUBSAMPLING, &subsamplinghor, &subsamplingver);
+
 	scanline = TIFFScanlineSize(tif);
 	fromskew = (w < imagewidth ? imagewidth - w : 0);
 	for (row = 0; row < h; row += nrow)
@@ -879,7 +936,8 @@
 			break;
 		}
 
-		pos = ((row + img->row_offset) % rowsperstrip) * scanline;
+		pos = ((row + img->row_offset) % rowsperstrip) * scanline + \
+			((tmsize_t) img->col_offset * img->samplesperpixel);
 		(*put)(img, raster+y*w, 0, y, w, nrow, fromskew, toskew, buf + pos);
 		y += (flip & FLIP_VERTICALLY ? -(int32) nrow : (int32) nrow);
 	}
@@ -1010,7 +1068,8 @@
 			}
 		}
 
-		pos = ((row + img->row_offset) % rowsperstrip) * scanline;
+		pos = ((row + img->row_offset) % rowsperstrip) * scanline + \
+			((tmsize_t) img->col_offset * img->samplesperpixel);
 		(*put)(img, raster+y*w, 0, y, w, nrow, fromskew, toskew, p0 + pos, p1 + pos,
 		    p2 + pos, (alpha?(pa+pos):NULL));
 		y += (flip & FLIP_VERTICALLY ? -(int32) nrow : (int32) nrow);
@@ -1443,79 +1502,24 @@
  *
  * NB: The conversion of CMYK->RGB is *very* crude.
  */
-/*DECLAREContigPutFunc(putRGBcontig8bitCMYKtile)
+DECLAREContigPutFunc(putRGBcontig8bitCMYKtile)
 {
     int samplesperpixel = img->samplesperpixel;
     uint16 r, g, b, k;
-	
+
     (void) x; (void) y;
     fromskew *= samplesperpixel;
     while (h-- > 0) {
-		UNROLL8(w, NOP,
-	 	    k = 255 - pp[3];
-	 	    r = (k*(255-pp[0]))/255;
-	 	    g = (k*(255-pp[1]))/255;
-	 	    b = (k*(255-pp[2]))/255;
-		*cp++ = PACK(r, g, b);
-		pp += samplesperpixel);
-		cp += toskew;
-		pp += fromskew;
-}*/
-/* Modify in 20090723 by Sunliang.Liu */
-DECLAREContigPutFunc(putRGBcontig8bitCMYKtile)
-{
-	int samplesperpixel = img->samplesperpixel;
-	uint8 r, g, b, k;
-
-	(void) x; (void) y;
-	fromskew *= samplesperpixel;
-	while (h-- > 0) {
-		UNROLL8(w, NOP,
-			if(!TIFFCmyk2Rgb(img->tif->tif_clientdata,pp[0],pp[1],pp[2],pp[3],
-				&r,&g,&b)){
-					k = 255 - pp[3];
-					r = (k*(255-pp[0]))/255;
-					g = (k*(255-pp[1]))/255;
-					b = (k*(255-pp[2]))/255;
-			}
-
-			*cp++ = PACK(r, g, b);
-			pp += samplesperpixel);
-			cp += toskew;
-			pp += fromskew;
-	}
-}
-
-/*
- * 16-bit packed CMYK samples w/o Map => RGB(8-bit)
- *
- * NB: The conversion of CMYK->RGB is *very* crude.
- */
-DECLAREContigPutFunc(putRGBcontig16bitCMYKtile)
-{
-	int samplesperpixel = img->samplesperpixel;
-	uint16* wp = (uint16*)pp;
-	uint8 C, M, Y, K;
-	uint8 r, g, b;
-
-	(void) x; (void) y;
-	fromskew *= samplesperpixel;
-	while (h-- > 0) {
-		UNROLL8(w, NOP,
-			C = wp[0]>>8;M = wp[1]>>8;Y = wp[2]>>8;K = wp[3]>>8;
-		if(!TIFFCmyk2Rgb(img->tif->tif_clientdata,C,M,Y,K,
-			&r,&g,&b)){
-				K = 255 - K;
-				r = (K*(255-C))/255;
-				g = (K*(255-M))/255;
-				b = (K*(255-Y))/255;
-		}
-
-		*cp++ = PACK(r, g, b);
-		wp += samplesperpixel);
-		cp += toskew;
-		wp += fromskew;
-	}
+	UNROLL8(w, NOP,
+	    k = 255 - pp[3];
+	    r = (k*(255-pp[0]))/255;
+	    g = (k*(255-pp[1]))/255;
+	    b = (k*(255-pp[2]))/255;
+	    *cp++ = PACK(r, g, b);
+	    pp += samplesperpixel);
+	cp += toskew;
+	pp += fromskew;
+    }
 }
 
 /*
@@ -1523,7 +1527,6 @@
  *
  * NB: The conversion of CMYK->RGB is *very* crude.
  */
-/*
 DECLAREContigPutFunc(putRGBcontig8bitCMYKMaptile)
 {
     int samplesperpixel = img->samplesperpixel;
@@ -1544,64 +1547,6 @@
 	pp += fromskew;
 	cp += toskew;
     }
-}*/
-/* Modify in 20090723 by Sunliang.Liu */
-DECLAREContigPutFunc(putRGBcontig8bitCMYKMaptile)
-{
-	int samplesperpixel = img->samplesperpixel;
-	TIFFRGBValue* Map = img->Map;
-	uint8 r, g, b, k;
-
-	(void) y;
-	fromskew *= samplesperpixel;
-	while (h-- > 0) {
-		for (x = w; x-- > 0;) {
-			if(!TIFFCmyk2Rgb(img->tif->tif_clientdata,pp[0],pp[1],pp[2],pp[3],
-				&r,&g,&b)){
-					k = 255 - pp[3];
-					r = (k*(255-pp[0]))/255;
-					g = (k*(255-pp[1]))/255;
-					b = (k*(255-pp[2]))/255;
-			}
-			*cp++ = PACK(Map[r], Map[g], Map[b]);
-			pp += samplesperpixel;
-		}
-		pp += fromskew;
-		cp += toskew;
-	}
-}
-
-/*
- * 16-bit packed CMYK samples w/Map => RGB(8-bit)
- *
- * NB: The conversion of CMYK->RGB is *very* crude.
- */
-DECLAREContigPutFunc(putRGBcontig16bitCMYKMaptile)
-{
-	int samplesperpixel = img->samplesperpixel;
-	TIFFRGBValue* Map = img->Map;
-	uint16* wp = (uint16*)pp;
-	uint8 C, M, Y, K;
-	uint8 r, g, b;
-
-	(void) y;
-	fromskew *= samplesperpixel;
-	while (h-- > 0) {
-		for (x = w; x-- > 0;) {
-			C = wp[0]>>8;M = wp[1]>>8;Y = wp[2]>>8;K = wp[3]>>8;
-			if(!TIFFCmyk2Rgb(img->tif->tif_clientdata,C,M,Y,K,
-				&r,&g,&b)){
-					K = 255 - K;
-					r = (K*(255-C))/255;
-					g = (K*(255-M))/255;
-					b = (K*(255-Y))/255;
-			}
-			*cp++ = PACK(Map[r], Map[g], Map[b]);
-			wp += samplesperpixel;
-		}
-		wp += fromskew;
-		cp += toskew;
-	}
 }
 
 #define	DECLARESepPutFunc(name) \
@@ -1966,7 +1911,7 @@
 
     (void) y;
     fromskew = (fromskew * 10) / 4;
-    if ((h & 3) == 0 && (w & 1) == 0) {
+    if ((w & 3) == 0 && (h & 1) == 0) {
         for (; h >= 2; h -= 2) {
             x = w>>2;
             do {
@@ -2043,7 +1988,7 @@
     /* XXX adjust fromskew */
     do {
 	x = w>>2;
-	do {
+	while(x>0) {
 	    int32 Cb = pp[4];
 	    int32 Cr = pp[5];
 
@@ -2054,7 +1999,8 @@
 
 	    cp += 4;
 	    pp += 6;
-	} while (--x);
+		x--;
+	}
 
         if( (w&3) != 0 )
         {
@@ -2145,7 +2091,7 @@
 	fromskew = (fromskew * 4) / 2;
 	do {
 		x = w>>1;
-		do {
+		while(x>0) {
 			int32 Cb = pp[2];
 			int32 Cr = pp[3];
 
@@ -2154,7 +2100,8 @@
 
 			cp += 2;
 			pp += 4;
-		} while (--x);
+			x --;
+		}
 
 		if( (w&1) != 0 )
 		{
@@ -2312,7 +2259,7 @@
 		return NULL;
 	}
 
-	return (tileContigRoutine)putcontig8bitCIELab;
+	return putcontig8bitCIELab;
 }
 
 /*
@@ -2594,21 +2541,14 @@
 		case PHOTOMETRIC_SEPARATED:
 			if (buildMap(img)) {
 				if (img->bitspersample == 8) {
-				if (!img->Map)
-					img->put.contig = putRGBcontig8bitCMYKtile;
-				else
-					img->put.contig = putRGBcontig8bitCMYKMaptile;
+					if (!img->Map)
+						img->put.contig = putRGBcontig8bitCMYKtile;
+					else
+						img->put.contig = putRGBcontig8bitCMYKMaptile;
+				}
 			}
-			else if(img->bitspersample == 16) /*LiuSunliang added 16bpp CMYK support.*/
-			{
-				if (!img->Map)
-					img->put.contig = putRGBcontig16bitCMYKtile;
-				else
-					img->put.contig = putRGBcontig16bitCMYKMaptile;
-			}
-		}
-		break;
-	case PHOTOMETRIC_PALETTE:
+			break;
+		case PHOTOMETRIC_PALETTE:
 			if (buildMap(img)) {
 				switch (img->bitspersample) {
 					case 8:
@@ -2662,7 +2602,7 @@
 					 * must always be <= horizontal subsampling; so
 					 * there are only a few possibilities and we just
 					 * enumerate the cases.
-					 * Joris: added support for the [1,2] case, nonetheless, to accomodate
+					 * Joris: added support for the [1,2] case, nonetheless, to accommodate
 					 * some OJPEG files
 					 */
 					uint16 SubsamplingHor;
@@ -2986,4 +2926,3 @@
  * fill-column: 78
  * End:
  */
-
diff --git a/third_party/tiff_v403/tif_jpeg.c b/third_party/libtiff/tif_jpeg.c
similarity index 88%
rename from third_party/tiff_v403/tif_jpeg.c
rename to third_party/libtiff/tif_jpeg.c
index d6f37df..6659909 100644
--- a/third_party/tiff_v403/tif_jpeg.c
+++ b/third_party/libtiff/tif_jpeg.c
@@ -1,4 +1,4 @@
-/* $Id: tif_jpeg.c,v 1.111 2012-07-06 18:48:04 bfriesen Exp $ */
+/* $Id: tif_jpeg.c,v 1.119 2015-08-15 20:13:07 bfriesen Exp $ */
 
 /*
  * Copyright (c) 1994-1997 Sam Leffler
@@ -23,6 +23,7 @@
  * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE 
  * OF THIS SOFTWARE.
  */
+
 #define WIN32_LEAN_AND_MEAN
 #define VC_EXTRALEAN
 
@@ -77,7 +78,7 @@
 */
 
 /* Define "boolean" as unsigned char, not int, per Windows custom. */
-#if defined(WIN32) && !defined(__MINGW32__)
+#if defined(__WIN32__) && !defined(__MINGW32__)
 # ifndef __RPCNDR_H__            /* don't conflict if rpcndr.h already read */
    typedef unsigned char boolean;
 # endif
@@ -259,6 +260,9 @@
 	sp->err.error_exit = TIFFjpeg_error_exit;
 	sp->err.output_message = TIFFjpeg_output_message;
 
+	/* set client_data to avoid UMR warning from tools like Purify */
+	sp->cinfo.c.client_data = NULL;
+
 	return CALLVJPEG(sp, jpeg_create_compress(&sp->cinfo.c));
 }
 
@@ -270,6 +274,9 @@
 	sp->err.error_exit = TIFFjpeg_error_exit;
 	sp->err.output_message = TIFFjpeg_output_message;
 
+	/* set client_data to avoid UMR warning from tools like Purify */
+	sp->cinfo.d.client_data = NULL;
+
 	return CALLVJPEG(sp, jpeg_create_decompress(&sp->cinfo.d));
 }
 
@@ -665,7 +672,9 @@
 
 #define JPEG_MARKER_SOF0 0xC0
 #define JPEG_MARKER_SOF1 0xC1
-#define JPEG_MARKER_SOF3 0xC3
+#define JPEG_MARKER_SOF2 0xC2
+#define JPEG_MARKER_SOF9 0xC9
+#define JPEG_MARKER_SOF10 0xCA
 #define JPEG_MARKER_DHT 0xC4
 #define JPEG_MARKER_SOI 0xD8
 #define JPEG_MARKER_SOS 0xDA
@@ -736,6 +745,7 @@
         _TIFFFillStriles( tif );
         
         if( tif->tif_dir.td_stripbytecount == NULL
+            || tif->tif_dir.td_stripoffset == NULL
             || tif->tif_dir.td_stripbytecount[0] == 0 )
         {
             /* Do not even try to check if the first strip/tile does not
@@ -823,8 +833,11 @@
 						JPEGFixupTagsSubsamplingSkip(data,n);
 				}
 				break;
-			case JPEG_MARKER_SOF0:
-			case JPEG_MARKER_SOF1:
+			case JPEG_MARKER_SOF0: /* Baseline sequential Huffman */
+			case JPEG_MARKER_SOF1: /* Extended sequential Huffman */
+			case JPEG_MARKER_SOF2: /* Progressive Huffman: normally not allowed by TechNote, but that doesn't hurt supporting it */
+			case JPEG_MARKER_SOF9: /* Extended sequential arithmetic */
+			case JPEG_MARKER_SOF10: /* Progressive arithmetic: normally not allowed by TechNote, but that doesn't hurt supporting it */
 				/* this marker contains the subsampling factors we're scanning for */
 				{
 					uint16 n;
@@ -999,7 +1012,7 @@
 /*
  * Set up for decoding a strip or tile.
  */
-static int
+/*ARGSUSED*/ static int
 JPEGPreDecode(TIFF* tif, uint16 s)
 {
 	JPEGState *sp = JState(tif);
@@ -1175,6 +1188,63 @@
  * Decode a chunk of pixels.
  * "Standard" case: returned data is not downsampled.
  */
+#if !JPEG_LIB_MK1_OR_12BIT
+static int
+JPEGDecode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
+{
+	JPEGState *sp = JState(tif);
+	tmsize_t nrows;
+	(void) s;
+
+        /*
+        ** Update available information, buffer may have been refilled
+        ** between decode requests
+        */
+	sp->src.next_input_byte = (const JOCTET*) tif->tif_rawcp;
+	sp->src.bytes_in_buffer = (size_t) tif->tif_rawcc;
+
+        if( sp->bytesperline == 0 )
+                return 0;
+        
+	nrows = cc / sp->bytesperline;
+	if (cc % sp->bytesperline)
+		TIFFWarningExt(tif->tif_clientdata, tif->tif_name,
+                               "fractional scanline not read");
+
+	if( nrows > (tmsize_t) sp->cinfo.d.image_height )
+		nrows = sp->cinfo.d.image_height;
+
+	/* data is expected to be read in multiples of a scanline */
+	if (nrows)
+        {
+                do
+                {
+                        /*
+                         * In the libjpeg6b-9a 8bit case.  We read directly into
+                         * the TIFF buffer.
+                         */
+                        JSAMPROW bufptr = (JSAMPROW)buf;
+
+                        if (TIFFjpeg_read_scanlines(sp, &bufptr, 1) != 1)
+                                return (0);
+
+                        ++tif->tif_row;
+                        buf += sp->bytesperline;
+                        cc -= sp->bytesperline;
+                } while (--nrows > 0);
+        }
+
+        /* Update information on consumed data */
+        tif->tif_rawcp = (uint8*) sp->src.next_input_byte;
+        tif->tif_rawcc = sp->src.bytes_in_buffer;
+                
+	/* Close down the decompressor if we've finished the strip or tile. */
+	return sp->cinfo.d.output_scanline < sp->cinfo.d.output_height
+                || TIFFjpeg_finish_decompress(sp);
+}
+#endif /* !JPEG_LIB_MK1_OR_12BIT */
+
+#if JPEG_LIB_MK1_OR_12BIT
 /*ARGSUSED*/ static int
 JPEGDecode(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
 {
@@ -1194,91 +1264,81 @@
         
 	nrows = cc / sp->bytesperline;
 	if (cc % sp->bytesperline)
-		TIFFWarningExt(tif->tif_clientdata, tif->tif_name, "fractional scanline not read");
+		TIFFWarningExt(tif->tif_clientdata, tif->tif_name,
+                               "fractional scanline not read");
 
 	if( nrows > (tmsize_t) sp->cinfo.d.image_height )
 		nrows = sp->cinfo.d.image_height;
 
 	/* data is expected to be read in multiples of a scanline */
 	if (nrows)
-	{
-		JSAMPROW line_work_buf = NULL;
+        {
+                JSAMPROW line_work_buf = NULL;
 
-		/*
-		 * For 6B, only use temporary buffer for 12 bit imagery.
-		 * For Mk1 always use it.
-		 */
-#if !defined(JPEG_LIB_MK1)
-		if( sp->cinfo.d.data_precision == 12 )
-#endif
-		{
-			line_work_buf = (JSAMPROW)
-			    _TIFFmalloc(sizeof(short) * sp->cinfo.d.output_width
-			    * sp->cinfo.d.num_components );
-		}
+                /*
+                 * For 6B, only use temporary buffer for 12 bit imagery.
+                 * For Mk1 always use it.
+                 */
+                if( sp->cinfo.d.data_precision == 12 )
+                {
+                        line_work_buf = (JSAMPROW)
+                                _TIFFmalloc(sizeof(short) * sp->cinfo.d.output_width
+                                            * sp->cinfo.d.num_components );
+                }
 
-		do {
-			if( line_work_buf != NULL )
-			{
-				/*
-				 * In the MK1 case, we aways read into a 16bit buffer, and then
-				 * pack down to 12bit or 8bit.  In 6B case we only read into 16
-				 * bit buffer for 12bit data, which we need to repack.
-				*/
-				if (TIFFjpeg_read_scanlines(sp, &line_work_buf, 1) != 1)
-					return (0);
+               do
+               {
+                       if( line_work_buf != NULL )
+                       {
+                               /*
+                                * In the MK1 case, we aways read into a 16bit
+                                * buffer, and then pack down to 12bit or 8bit.
+                                * In 6B case we only read into 16 bit buffer
+                                * for 12bit data, which we need to repack.
+                                */
+                               if (TIFFjpeg_read_scanlines(sp, &line_work_buf, 1) != 1)
+                                       return (0);
 
-				if( sp->cinfo.d.data_precision == 12 )
-				{
-					int value_pairs = (sp->cinfo.d.output_width
-					    * sp->cinfo.d.num_components) / 2;
-					int iPair;
+                               if( sp->cinfo.d.data_precision == 12 )
+                               {
+                                       int value_pairs = (sp->cinfo.d.output_width
+                                                          * sp->cinfo.d.num_components) / 2;
+                                       int iPair;
 
-					for( iPair = 0; iPair < value_pairs; iPair++ )
-					{
-						unsigned char *out_ptr =
-						    ((unsigned char *) buf) + iPair * 3;
-						JSAMPLE *in_ptr = line_work_buf + iPair * 2;
+                                       for( iPair = 0; iPair < value_pairs; iPair++ )
+                                       {
+                                               unsigned char *out_ptr =
+                                                       ((unsigned char *) buf) + iPair * 3;
+                                               JSAMPLE *in_ptr = line_work_buf + iPair * 2;
 
-						out_ptr[0] = (in_ptr[0] & 0xff0) >> 4;
-						out_ptr[1] = ((in_ptr[0] & 0xf) << 4)
-						    | ((in_ptr[1] & 0xf00) >> 8);
-						out_ptr[2] = ((in_ptr[1] & 0xff) >> 0);
-					}
-				}
-				else if( sp->cinfo.d.data_precision == 8 )
-				{
-					int value_count = (sp->cinfo.d.output_width
-					    * sp->cinfo.d.num_components);
-					int iValue;
+                                               out_ptr[0] = (in_ptr[0] & 0xff0) >> 4;
+                                               out_ptr[1] = ((in_ptr[0] & 0xf) << 4)
+                                                       | ((in_ptr[1] & 0xf00) >> 8);
+                                               out_ptr[2] = ((in_ptr[1] & 0xff) >> 0);
+                                       }
+                               }
+                               else if( sp->cinfo.d.data_precision == 8 )
+                               {
+                                       int value_count = (sp->cinfo.d.output_width
+                                                          * sp->cinfo.d.num_components);
+                                       int iValue;
 
-					for( iValue = 0; iValue < value_count; iValue++ )
-					{
-						((unsigned char *) buf)[iValue] =
-						    line_work_buf[iValue] & 0xff;
-					}
-				}
-			}
-			else
-			{
-				/*
-				 * In the libjpeg6b 8bit case.  We read directly into the
-				 * TIFF buffer.
-				*/
-				JSAMPROW bufptr = (JSAMPROW)buf;
+                                       for( iValue = 0; iValue < value_count; iValue++ )
+                                       {
+                                               ((unsigned char *) buf)[iValue] =
+                                                       line_work_buf[iValue] & 0xff;
+                                       }
+                               }
+                       }
 
-				if (TIFFjpeg_read_scanlines(sp, &bufptr, 1) != 1)
-					return (0);
-			}
+                       ++tif->tif_row;
+                       buf += sp->bytesperline;
+                       cc -= sp->bytesperline;
+               } while (--nrows > 0);
 
-			++tif->tif_row;
-			buf += sp->bytesperline;
-			cc -= sp->bytesperline;
-		} while (--nrows > 0);
-
-		if( line_work_buf != NULL )
-			_TIFFfree( line_work_buf );
-	}
+               if( line_work_buf != NULL )
+                       _TIFFfree( line_work_buf );
+        }
 
         /* Update information on consumed data */
         tif->tif_rawcp = (uint8*) sp->src.next_input_byte;
@@ -1286,8 +1346,9 @@
                 
 	/* Close down the decompressor if we've finished the strip or tile. */
 	return sp->cinfo.d.output_scanline < sp->cinfo.d.output_height
-	    || TIFFjpeg_finish_decompress(sp);
+                || TIFFjpeg_finish_decompress(sp);
 }
+#endif /* JPEG_LIB_MK1_OR_12BIT */
 
 /*ARGSUSED*/ static int
 DecodeRowError(TIFF* tif, uint8* buf, tmsize_t cc, uint16 s)
@@ -1458,6 +1519,15 @@
 }
 
 static void
+suppress_quant_table (JPEGState* sp, int tblno)
+{
+	JQUANT_TBL* qtbl;
+
+	if ((qtbl = sp->cinfo.c.quant_tbl_ptrs[tblno]) != NULL)
+		qtbl->sent_table = TRUE;
+}
+
+static void
 unsuppress_huff_table (JPEGState* sp, int tblno)
 {
 	JHUFF_TBL* htbl;
@@ -1468,6 +1538,17 @@
 		htbl->sent_table = FALSE;
 }
 
+static void
+suppress_huff_table (JPEGState* sp, int tblno)
+{
+	JHUFF_TBL* htbl;
+
+	if ((htbl = sp->cinfo.c.dc_huff_tbl_ptrs[tblno]) != NULL)
+		htbl->sent_table = TRUE;
+	if ((htbl = sp->cinfo.c.ac_huff_tbl_ptrs[tblno]) != NULL)
+		htbl->sent_table = TRUE;
+}
+
 static int
 prepare_JPEGTables(TIFF* tif)
 {
@@ -1517,17 +1598,38 @@
 	assert(sp != NULL);
 	assert(!sp->cinfo.comm.is_decompressor);
 
+	sp->photometric = td->td_photometric;
+
 	/*
 	 * Initialize all JPEG parameters to default values.
 	 * Note that jpeg_set_defaults needs legal values for
 	 * in_color_space and input_components.
 	 */
-	sp->cinfo.c.in_color_space = JCS_UNKNOWN;
-	sp->cinfo.c.input_components = 1;
+	if (td->td_planarconfig == PLANARCONFIG_CONTIG) {
+		sp->cinfo.c.input_components = td->td_samplesperpixel;
+		if (sp->photometric == PHOTOMETRIC_YCBCR) {
+			if (sp->jpegcolormode == JPEGCOLORMODE_RGB) {
+				sp->cinfo.c.in_color_space = JCS_RGB;
+			} else {
+				sp->cinfo.c.in_color_space = JCS_YCbCr;
+			}
+		} else {
+			if ((td->td_photometric == PHOTOMETRIC_MINISWHITE || td->td_photometric == PHOTOMETRIC_MINISBLACK) && td->td_samplesperpixel == 1)
+				sp->cinfo.c.in_color_space = JCS_GRAYSCALE;
+			else if (td->td_photometric == PHOTOMETRIC_RGB && td->td_samplesperpixel == 3)
+				sp->cinfo.c.in_color_space = JCS_RGB;
+			else if (td->td_photometric == PHOTOMETRIC_SEPARATED && td->td_samplesperpixel == 4)
+				sp->cinfo.c.in_color_space = JCS_CMYK;
+			else
+				sp->cinfo.c.in_color_space = JCS_UNKNOWN;
+		}
+	} else {
+		sp->cinfo.c.input_components = 1;
+		sp->cinfo.c.in_color_space = JCS_UNKNOWN;
+	}
 	if (!TIFFjpeg_set_defaults(sp))
 		return (0);
 	/* Set per-file parameters */
-	sp->photometric = td->td_photometric;
 	switch (sp->photometric) {
 	case PHOTOMETRIC_YCBCR:
 		sp->h_sampling = td->td_ycbcrsubsampling[0];
@@ -1687,10 +1789,7 @@
 	if (td->td_planarconfig == PLANARCONFIG_CONTIG) {
 		sp->cinfo.c.input_components = td->td_samplesperpixel;
 		if (sp->photometric == PHOTOMETRIC_YCBCR) {
-			if (sp->jpegcolormode == JPEGCOLORMODE_RGB) {
-				sp->cinfo.c.in_color_space = JCS_RGB;
-			} else {
-				sp->cinfo.c.in_color_space = JCS_YCbCr;
+			if (sp->jpegcolormode != JPEGCOLORMODE_RGB) {
 				if (sp->h_sampling != 1 || sp->v_sampling != 1)
 					downsampled_input = TRUE;
 			}
@@ -1703,21 +1802,11 @@
 			sp->cinfo.c.comp_info[0].h_samp_factor = sp->h_sampling;
 			sp->cinfo.c.comp_info[0].v_samp_factor = sp->v_sampling;
 		} else {
-			if ((td->td_photometric == PHOTOMETRIC_MINISWHITE || td->td_photometric == PHOTOMETRIC_MINISBLACK) && td->td_samplesperpixel == 1)
-				sp->cinfo.c.in_color_space = JCS_GRAYSCALE;
-			else if (td->td_photometric == PHOTOMETRIC_RGB && td->td_samplesperpixel == 3)
-				sp->cinfo.c.in_color_space = JCS_RGB;
-			else if (td->td_photometric == PHOTOMETRIC_SEPARATED && td->td_samplesperpixel == 4)
-				sp->cinfo.c.in_color_space = JCS_CMYK;
-			else
-				sp->cinfo.c.in_color_space = JCS_UNKNOWN;
 			if (!TIFFjpeg_set_colorspace(sp, sp->cinfo.c.in_color_space))
 				return (0);
 			/* jpeg_set_colorspace set all sampling factors to 1 */
 		}
 	} else {
-		sp->cinfo.c.input_components = 1;
-		sp->cinfo.c.in_color_space = JCS_UNKNOWN;
 		if (!TIFFjpeg_set_colorspace(sp, JCS_UNKNOWN))
 			return (0);
 		sp->cinfo.c.comp_info[0].component_id = s;
@@ -1732,14 +1821,30 @@
 	sp->cinfo.c.write_JFIF_header = FALSE;
 	sp->cinfo.c.write_Adobe_marker = FALSE;
 	/* set up table handling correctly */
-        if (!TIFFjpeg_set_quality(sp, sp->jpegquality, FALSE))
+	/* calling TIFFjpeg_set_quality() causes quantization tables to be flagged */
+	/* as being to be emitted, which we don't want in the JPEGTABLESMODE_QUANT */
+	/* mode, so we must manually suppress them. However TIFFjpeg_set_quality() */
+	/* should really be called when dealing with files with directories with */
+	/* mixed qualities. see http://trac.osgeo.org/gdal/ticket/3539 */
+	if (!TIFFjpeg_set_quality(sp, sp->jpegquality, FALSE))
 		return (0);
-	if (! (sp->jpegtablesmode & JPEGTABLESMODE_QUANT)) {
+	if (sp->jpegtablesmode & JPEGTABLESMODE_QUANT) {
+		suppress_quant_table(sp, 0);
+		suppress_quant_table(sp, 1);
+	}
+	else {
 		unsuppress_quant_table(sp, 0);
 		unsuppress_quant_table(sp, 1);
 	}
 	if (sp->jpegtablesmode & JPEGTABLESMODE_HUFF)
+	{
+		/* Explicit suppression is only needed if we did not go through the */
+		/* prepare_JPEGTables() code path, which may be the case if updating */
+		/* an existing file */
+		suppress_huff_table(sp, 0);
+		suppress_huff_table(sp, 1);
 		sp->cinfo.c.optimize_coding = FALSE;
+	}
 	else
 		sp->cinfo.c.optimize_coding = TRUE;
 	if (downsampled_input) {
@@ -1796,9 +1901,16 @@
 
         if( sp->cinfo.c.data_precision == 12 )
         {
-            line16_count = (int)((sp->bytesperline * 2) / 3);
+            line16_count = (sp->bytesperline * 2) / 3;
             line16 = (short *) _TIFFmalloc(sizeof(short) * line16_count);
-	    // FIXME: undiagnosed malloc failure
+            if (!line16)
+            {
+                TIFFErrorExt(tif->tif_clientdata,
+			     "JPEGEncode",
+                             "Failed to allocate memory");
+
+                return 0;
+            }
         }
             
 	while (nrows-- > 0) {
@@ -1973,13 +2085,10 @@
 	tif->tif_tagmethods.vgetfield = sp->vgetparent;
 	tif->tif_tagmethods.vsetfield = sp->vsetparent;
 	tif->tif_tagmethods.printdir = sp->printdir;
-
-	if( sp != NULL ) {
-		if( sp->cinfo_initialized )
-		    TIFFjpeg_destroy(sp);	/* release libjpeg resources */
-		if (sp->jpegtables)		/* tag value */
-			_TIFFfree(sp->jpegtables);
-	}
+        if( sp->cinfo_initialized )
+                TIFFjpeg_destroy(sp);	/* release libjpeg resources */
+        if (sp->jpegtables)		/* tag value */
+                _TIFFfree(sp->jpegtables);
 	_TIFFfree(tif->tif_data);	/* release local state */
 	tif->tif_data = NULL;
 
@@ -2291,8 +2400,17 @@
 */
             sp->jpegtables_length = SIZE_OF_JPEGTABLES;
             sp->jpegtables = (void *) _TIFFmalloc(sp->jpegtables_length);
-	    // FIXME: NULL-deref after malloc failure
-	    _TIFFmemset(sp->jpegtables, 0, SIZE_OF_JPEGTABLES);
+            if (sp->jpegtables)
+            {
+                _TIFFmemset(sp->jpegtables, 0, SIZE_OF_JPEGTABLES);
+            }
+            else
+            {
+                TIFFErrorExt(tif->tif_clientdata,
+			     "TIFFInitJPEG",
+                             "Failed to allocate memory for JPEG tables");
+                return 0;
+            }
 #undef SIZE_OF_JPEGTABLES
         }
 
@@ -2309,4 +2427,3 @@
  * fill-column: 78
  * End:
  */
-
diff --git a/third_party/tiff_v403/tif_luv.c b/third_party/libtiff/tif_luv.c
similarity index 98%
rename from third_party/tiff_v403/tif_luv.c
rename to third_party/libtiff/tif_luv.c
index 88f4ee8..4e328ba 100644
--- a/third_party/tiff_v403/tif_luv.c
+++ b/third_party/libtiff/tif_luv.c
@@ -1,4 +1,4 @@
-/* $Id: tif_luv.c,v 1.35 2011-04-02 20:54:09 bfriesen Exp $ */
+/* $Id: tif_luv.c,v 1.40 2015-06-21 01:09:09 bfriesen Exp $ */
 
 /*
  * Copyright (c) 1997 Greg Ward Larson
@@ -23,6 +23,7 @@
  * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE 
  * OF THIS SOFTWARE.
  */
+
 #include "tiffiop.h"
 #ifdef LOGLUV_SUPPORT
 
@@ -378,6 +379,9 @@
 {
 	tmsize_t rowlen = TIFFScanlineSize(tif);
 
+        if (rowlen == 0)
+                return 0;
+
 	assert(cc%rowlen == 0);
 	while (cc && (*tif->tif_decoderow)(tif, bp, rowlen, s))
 		bp += rowlen, cc -= rowlen;
@@ -394,6 +398,9 @@
 {
 	tmsize_t rowlen = TIFFTileRowSize(tif);
 
+        if (rowlen == 0)
+                return 0;
+
 	assert(cc%rowlen == 0);
 	while (cc && (*tif->tif_decoderow)(tif, bp, rowlen, s))
 		bp += rowlen, cc -= rowlen;
@@ -643,6 +650,9 @@
 {
 	tmsize_t rowlen = TIFFScanlineSize(tif);
 
+        if (rowlen == 0)
+                return 0;
+
 	assert(cc%rowlen == 0);
 	while (cc && (*tif->tif_encoderow)(tif, bp, rowlen, s) == 1)
 		bp += rowlen, cc -= rowlen;
@@ -658,6 +668,9 @@
 {
 	tmsize_t rowlen = TIFFTileRowSize(tif);
 
+        if (rowlen == 0)
+                return 0;
+
 	assert(cc%rowlen == 0);
 	while (cc && (*tif->tif_encoderow)(tif, bp, rowlen, s) == 1)
 		bp += rowlen, cc -= rowlen;
@@ -682,9 +695,9 @@
 #ifndef M_PI
 #define M_PI		3.14159265358979323846
 #endif
-#ifndef log2
+#undef log2 /* Conflict with C'99 function */
 #define log2(x)		((1./M_LN2)*log(x))
-#endif
+#undef exp2  /* Conflict with C'99 function */
 #define exp2(x)		exp(M_LN2*(x))
 
 #define itrunc(x,m)	((m)==SGILOGENCODE_NODITHER ? \
@@ -1682,4 +1695,3 @@
  * fill-column: 78
  * End:
  */
-
diff --git a/third_party/tiff_v403/tif_lzw.c b/third_party/libtiff/tif_lzw.c
similarity index 95%
rename from third_party/tiff_v403/tif_lzw.c
rename to third_party/libtiff/tif_lzw.c
index 3a6f4c8..9b76dd0 100644
--- a/third_party/tiff_v403/tif_lzw.c
+++ b/third_party/libtiff/tif_lzw.c
@@ -1,4 +1,4 @@
-/* $Id: tif_lzw.c,v 1.45 2011-04-02 20:54:09 bfriesen Exp $ */
+/* $Id: tif_lzw.c,v 1.49 2015-08-30 21:07:44 erouault Exp $ */
 
 /*
  * Copyright (c) 1988-1997 Sam Leffler
@@ -23,6 +23,7 @@
  * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE 
  * OF THIS SOFTWARE.
  */
+
 #include "tiffiop.h"
 #ifdef LZW_SUPPORT
 /*
@@ -93,7 +94,7 @@
 	unsigned short  nbits;          /* # of bits/code */
 	unsigned short  maxcode;        /* maximum code for lzw_nbits */
 	unsigned short  free_ent;       /* next free entry in hash table */
-	long            nextdata;       /* next bits of i/o */
+	unsigned long   nextdata;       /* next bits of i/o */
 	long            nextbits;       /* # of valid bits in lzw_nextdata */
 
 	int             rw_mode;        /* preserve rw_mode from init */
@@ -267,6 +268,8 @@
 	if( sp->dec_codetab == NULL )
         {
             tif->tif_setupdecode( tif );
+	    if( sp->dec_codetab == NULL )
+		return (0);
         }
 
 	/*
@@ -364,7 +367,8 @@
 	unsigned char *bp;
 	hcode_t code;
 	int len;
-	long nbits, nextbits, nextdata, nbitsmask;
+	long nbits, nextbits, nbitsmask;
+        unsigned long nextdata;
 	code_t *codep, *free_entp, *maxcodep, *oldcodep;
 
 	(void) s;
@@ -433,16 +437,18 @@
 		if (code == CODE_EOI)
 			break;
 		if (code == CODE_CLEAR) {
-			free_entp = sp->dec_codetab + CODE_FIRST;
-			_TIFFmemset(free_entp, 0,
-				    (CSIZE - CODE_FIRST) * sizeof (code_t));
-			nbits = BITS_MIN;
-			nbitsmask = MAXCODE(BITS_MIN);
-			maxcodep = sp->dec_codetab + nbitsmask-1;
-			NextCode(tif, sp, bp, code, GetNextCode);
+			do {
+				free_entp = sp->dec_codetab + CODE_FIRST;
+				_TIFFmemset(free_entp, 0,
+					    (CSIZE - CODE_FIRST) * sizeof (code_t));
+				nbits = BITS_MIN;
+				nbitsmask = MAXCODE(BITS_MIN);
+				maxcodep = sp->dec_codetab + nbitsmask-1;
+				NextCode(tif, sp, bp, code, GetNextCode);
+			} while (code == CODE_CLEAR);	/* consecutive CODE_CLEAR codes */
 			if (code == CODE_EOI)
 				break;
-			if (code >= CODE_CLEAR) {
+			if (code > CODE_CLEAR) {
 				TIFFErrorExt(tif->tif_clientdata, tif->tif_name,
 				"LZWDecode: Corrupted LZW table at scanline %d",
 					     tif->tif_row);
@@ -652,16 +658,18 @@
 		if (code == CODE_EOI)
 			break;
 		if (code == CODE_CLEAR) {
-			free_entp = sp->dec_codetab + CODE_FIRST;
-			_TIFFmemset(free_entp, 0,
-				    (CSIZE - CODE_FIRST) * sizeof (code_t));
-			nbits = BITS_MIN;
-			nbitsmask = MAXCODE(BITS_MIN);
-			maxcodep = sp->dec_codetab + nbitsmask;
-			NextCode(tif, sp, bp, code, GetNextCodeCompat);
+			do {
+				free_entp = sp->dec_codetab + CODE_FIRST;
+				_TIFFmemset(free_entp, 0,
+					    (CSIZE - CODE_FIRST) * sizeof (code_t));
+				nbits = BITS_MIN;
+				nbitsmask = MAXCODE(BITS_MIN);
+				maxcodep = sp->dec_codetab + nbitsmask;
+				NextCode(tif, sp, bp, code, GetNextCodeCompat);
+			} while (code == CODE_CLEAR);	/* consecutive CODE_CLEAR codes */
 			if (code == CODE_EOI)
 				break;
-			if (code >= CODE_CLEAR) {
+			if (code > CODE_CLEAR) {
 				TIFFErrorExt(tif->tif_clientdata, tif->tif_name,
 				"LZWDecode: Corrupted LZW table at scanline %d",
 					     tif->tif_row);
@@ -829,13 +837,15 @@
 	} else							\
 		rat = (incount<<8) / outcount;			\
 }
+
+/* Explicit 0xff masking to make icc -check=conversions happy */
 #define	PutNextCode(op, c) {					\
 	nextdata = (nextdata << nbits) | c;			\
 	nextbits += nbits;					\
-	*op++ = (unsigned char)(nextdata >> (nextbits-8));		\
+	*op++ = (unsigned char)((nextdata >> (nextbits-8))&0xff);		\
 	nextbits -= 8;						\
 	if (nextbits >= 8) {					\
-		*op++ = (unsigned char)(nextdata >> (nextbits-8));	\
+		*op++ = (unsigned char)((nextdata >> (nextbits-8))&0xff);	\
 		nextbits -= 8;					\
 	}							\
 	outcount += nbits;					\
@@ -865,7 +875,8 @@
 	hcode_t ent;
 	long disp;
 	long incount, outcount, checkpoint;
-	long nextdata, nextbits;
+	unsigned long nextdata;
+        long nextbits;
 	int free_ent, maxcode, nbits;
 	uint8* op;
 	uint8* limit;
@@ -1027,7 +1038,7 @@
 	register LZWCodecState *sp = EncoderState(tif);
 	uint8* op = tif->tif_rawcp;
 	long nextbits = sp->lzw_nextbits;
-	long nextdata = sp->lzw_nextdata;
+	unsigned long nextdata = sp->lzw_nextdata;
 	long outcount = sp->enc_outcount;
 	int nbits = sp->lzw_nbits;
 
@@ -1041,8 +1052,9 @@
 		sp->enc_oldcode = (hcode_t) -1;
 	}
 	PutNextCode(op, CODE_EOI);
+        /* Explicit 0xff masking to make icc -check=conversions happy */
 	if (nextbits > 0) 
-		*op++ = (unsigned char)(nextdata << (8-nextbits));
+		*op++ = (unsigned char)((nextdata << (8-nextbits))&0xff);
 	tif->tif_rawcc = (tmsize_t)(op - tif->tif_rawdata);
 	return (1);
 }
@@ -1164,4 +1176,3 @@
  * fill-column: 78
  * End:
  */
-
diff --git a/third_party/tiff_v403/tif_next.c b/third_party/libtiff/tif_next.c
similarity index 86%
rename from third_party/tiff_v403/tif_next.c
rename to third_party/libtiff/tif_next.c
index 9f2f6d5..17e0311 100644
--- a/third_party/tiff_v403/tif_next.c
+++ b/third_party/libtiff/tif_next.c
@@ -1,4 +1,4 @@
-/* $Id: tif_next.c,v 1.13 2010-03-10 18:56:48 bfriesen Exp $ */
+/* $Id: tif_next.c,v 1.16 2014-12-29 12:09:11 erouault Exp $ */
 
 /*
  * Copyright (c) 1988-1997 Sam Leffler
@@ -23,6 +23,7 @@
  * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE 
  * OF THIS SOFTWARE.
  */
+
 #include "tiffiop.h"
 #ifdef NEXT_SUPPORT
 /*
@@ -70,7 +71,7 @@
 		TIFFErrorExt(tif->tif_clientdata, module, "Fractional scanlines cannot be read");
 		return (0);
 	}
-	for (row = buf; occ > 0; occ -= scanline, row += scanline) {
+	for (row = buf; cc > 0 && occ > 0; occ -= scanline, row += scanline) {
 		n = *bp++, cc--;
 		switch (n) {
 		case LITERALROW:
@@ -89,6 +90,8 @@
 			 * The scanline has a literal span that begins at some
 			 * offset.
 			 */
+			if( cc < 4 )
+				goto bad;
 			off = (bp[0] * 256) + bp[1];
 			n = (bp[2] * 256) + bp[3];
 			if (cc < 4+n || off+n > scanline)
@@ -101,6 +104,8 @@
 		default: {
 			uint32 npixels = 0, grey;
 			uint32 imagewidth = tif->tif_dir.td_imagewidth;
+            if( isTiled(tif) )
+                imagewidth = tif->tif_dir.td_tilewidth;
 
 			/*
 			 * The scanline is composed of a sequence of constant
@@ -138,10 +143,27 @@
 	return (0);
 }
 
+static int
+NeXTPreDecode(TIFF* tif, uint16 s)
+{
+	static const char module[] = "NeXTPreDecode";
+	TIFFDirectory *td = &tif->tif_dir;
+	(void)s;
+
+	if( td->td_bitspersample != 2 )
+	{
+		TIFFErrorExt(tif->tif_clientdata, module, "Unsupported BitsPerSample = %d",
+					 td->td_bitspersample);
+		return (0);
+	}
+	return (1);
+}
+	
 int
 TIFFInitNeXT(TIFF* tif, int scheme)
 {
 	(void) scheme;
+	tif->tif_predecode = NeXTPreDecode;  
 	tif->tif_decoderow = NeXTDecode;  
 	tif->tif_decodestrip = NeXTDecode;  
 	tif->tif_decodetile = NeXTDecode;
@@ -157,4 +179,3 @@
  * fill-column: 78
  * End:
  */
-
diff --git a/third_party/tiff_v403/tif_ojpeg.c b/third_party/libtiff/tif_ojpeg.c
similarity index 97%
rename from third_party/tiff_v403/tif_ojpeg.c
rename to third_party/libtiff/tif_ojpeg.c
index 0a774a52..cc5449c 100644
--- a/third_party/tiff_v403/tif_ojpeg.c
+++ b/third_party/libtiff/tif_ojpeg.c
@@ -1,4 +1,4 @@
-/* $Id: tif_ojpeg.c,v 1.56 2012-05-24 03:15:18 fwarmerdam Exp $ */
+/* $Id: tif_ojpeg.c,v 1.60 2015-05-31 00:38:46 bfriesen Exp $ */
 
 /* WARNING: The type of JPEG encapsulation defined by the TIFF Version 6.0
    specification is now totally obsolete and deprecated for new applications and
@@ -39,7 +39,7 @@
    OF THIS SOFTWARE.
 
    Joris Van Damme and/or AWare Systems may be available for custom
-   developement. If you like what you see, and need anything similar or related,
+   development. If you like what you see, and need anything similar or related,
    contact <info@awaresystems.be>.
 */
 
@@ -120,7 +120,6 @@
    session.
 */
 
-
 #define WIN32_LEAN_AND_MEAN
 #define VC_EXTRALEAN
 
@@ -142,7 +141,7 @@
  * OJPEG_BUFFER: Define the size of the desired buffer here. Should be small enough so as to guarantee
  * 	instant processing, optimal streaming and optimal use of processor cache, but also big
  * 	enough so as to not result in significant call overhead. It should be at least a few
- * 	bytes to accomodate some structures (this is verified in asserts), but it would not be
+ * 	bytes to accommodate some structures (this is verified in asserts), but it would not be
  * 	sensible to make it this small anyway, and it should be at most 64K since it is indexed
  * 	with uint16. We recommend 2K.
  * EGYPTIANWALK: You could also define EGYPTIANWALK here, but it is not used anywhere and has
@@ -216,13 +215,17 @@
 #endif
 
 #if defined(USE_SYSTEM_LIBJPEG)
+#include <jerror.h>
 #include <jpeglib.h>
 #elif defined(USE_LIBJPEG_TURBO)
+#include "third_party/libjpeg_turbo/jerror.h"
 #include "third_party/libjpeg_turbo/jpeglib.h"
 #else
+#include "third_party/libjpeg/jerror.h"
 #include "third_party/libjpeg/jpeglib.h"
 #endif
 
+
 typedef struct jpeg_error_mgr jpeg_error_mgr;
 typedef struct jpeg_common_struct jpeg_common_struct;
 typedef struct jpeg_decompress_struct jpeg_decompress_struct;
@@ -439,8 +442,8 @@
 	}
 
 	/* state block */
-	sp = (OJPEGState*)_TIFFmalloc(sizeof(OJPEGState));		// // add (OJPEGState*) cast
-	if (sp == NULL)
+	sp=_TIFFmalloc(sizeof(OJPEGState));
+	if (sp==NULL)
 	{
 		TIFFErrorExt(tif->tif_clientdata,module,"No space for OJPEG state block");
 		return(0);
@@ -534,6 +537,8 @@
 	uint32 ma;
 	uint64* mb;
 	uint32 n;
+	const TIFFField* fip;
+
 	switch(tag)
 	{
 		case TIFFTAG_JPEGIFOFFSET:
@@ -603,7 +608,10 @@
 		default:
 			return (*sp->vsetparent)(tif,tag,ap);
 	}
-	TIFFSetFieldBit(tif,TIFFFieldWithTag(tif,tag)->field_bit);
+	fip = TIFFFieldWithTag(tif,tag);
+	if( fip == NULL ) /* shouldn't happen */
+	    return(0);
+	TIFFSetFieldBit(tif,fip->field_bit);
 	tif->tif_flags|=TIFF_DIRTYDIRECT;
 	return(1);
 }
@@ -767,9 +775,8 @@
 	uint32 m;
 	if (sp->skip_buffer==NULL)
 	{
-		// add (uint8*) cast
-		sp->skip_buffer = (uint8*)_TIFFmalloc(sp->bytes_per_line);
-		if (sp->skip_buffer == NULL)
+		sp->skip_buffer=_TIFFmalloc(sp->bytes_per_line);
+		if (sp->skip_buffer==NULL)
 		{
 			TIFFErrorExt(tif->tif_clientdata,module,"Out of memory");
 			return(0);
@@ -1193,7 +1200,7 @@
 			sp->subsampling_convert_ybuflen=sp->subsampling_convert_ylinelen*sp->subsampling_convert_ylines;
 			sp->subsampling_convert_cbuflen=sp->subsampling_convert_clinelen*sp->subsampling_convert_clines;
 			sp->subsampling_convert_ycbcrbuflen=sp->subsampling_convert_ybuflen+2*sp->subsampling_convert_cbuflen;
-			sp->subsampling_convert_ycbcrbuf = (uint8*)_TIFFmalloc(sp->subsampling_convert_ycbcrbuflen);	// add (uint8*) cast
+			sp->subsampling_convert_ycbcrbuf=_TIFFmalloc(sp->subsampling_convert_ycbcrbuflen);
 			if (sp->subsampling_convert_ycbcrbuf==0)
 			{
 				TIFFErrorExt(tif->tif_clientdata,module,"Out of memory");
@@ -1203,7 +1210,7 @@
 			sp->subsampling_convert_cbbuf=sp->subsampling_convert_ybuf+sp->subsampling_convert_ybuflen;
 			sp->subsampling_convert_crbuf=sp->subsampling_convert_cbbuf+sp->subsampling_convert_cbuflen;
 			sp->subsampling_convert_ycbcrimagelen=3+sp->subsampling_convert_ylines+2*sp->subsampling_convert_clines;
-			sp->subsampling_convert_ycbcrimage = (uint8**)_TIFFmalloc(sp->subsampling_convert_ycbcrimagelen * sizeof(uint8*));// add (uint8**) cast
+			sp->subsampling_convert_ycbcrimage=_TIFFmalloc(sp->subsampling_convert_ycbcrimagelen*sizeof(uint8*));
 			if (sp->subsampling_convert_ycbcrimage==0)
 			{
 				TIFFErrorExt(tif->tif_clientdata,module,"Out of memory");
@@ -1430,9 +1437,9 @@
 				TIFFErrorExt(tif->tif_clientdata,module,"Corrupt DQT marker in JPEG data");
 				return(0);
 			}
-			na = sizeof(uint32) + 69;
-			nb = (uint8*)_TIFFmalloc(na);	// add (uint8*) cast
-			if (nb == 0)
+			na=sizeof(uint32)+69;
+			nb=_TIFFmalloc(na);
+			if (nb==0)
 			{
 				TIFFErrorExt(tif->tif_clientdata,module,"Out of memory");
 				return(0);
@@ -1487,9 +1494,9 @@
 	}
 	else
 	{
-		na = sizeof(uint32) + 2 + m;
-		nb = (uint8*)_TIFFmalloc(na);	// add (uint8*) cast
-		if (nb == 0)
+		na=sizeof(uint32)+2+m;
+		nb=_TIFFmalloc(na);
+		if (nb==0)
 		{
 			TIFFErrorExt(tif->tif_clientdata,module,"Out of memory");
 			return(0);
@@ -1499,14 +1506,17 @@
 		nb[sizeof(uint32)+1]=JPEG_MARKER_DHT;
 		nb[sizeof(uint32)+2]=(m>>8);
 		nb[sizeof(uint32)+3]=(m&255);
-		if (OJPEGReadBlock(sp,m-2,&nb[sizeof(uint32)+4])==0)
+		if (OJPEGReadBlock(sp,m-2,&nb[sizeof(uint32)+4])==0) {
+                        _TIFFfree(nb);
 			return(0);
+                }
 		o=nb[sizeof(uint32)+4];
 		if ((o&240)==0)
 		{
 			if (3<o)
 			{
 				TIFFErrorExt(tif->tif_clientdata,module,"Corrupt DHT marker in JPEG data");
+                                _TIFFfree(nb);
 				return(0);
 			}
 			if (sp->dctable[o]!=0)
@@ -1518,12 +1528,14 @@
 			if ((o&240)!=16)
 			{
 				TIFFErrorExt(tif->tif_clientdata,module,"Corrupt DHT marker in JPEG data");
+                                _TIFFfree(nb);
 				return(0);
 			}
 			o&=15;
 			if (3<o)
 			{
 				TIFFErrorExt(tif->tif_clientdata,module,"Corrupt DHT marker in JPEG data");
+                                _TIFFfree(nb);
 				return(0);
 			}
 			if (sp->actable[o]!=0)
@@ -1763,7 +1775,7 @@
 				}
 			}
 			oa=sizeof(uint32)+69;
-			ob = (uint8*)_TIFFmalloc(oa);	// add (uint8*) cast
+			ob=_TIFFmalloc(oa);
 			if (ob==0)
 			{
 				TIFFErrorExt(tif->tif_clientdata,module,"Out of memory");
@@ -1776,7 +1788,7 @@
 			ob[sizeof(uint32)+3]=67;
 			ob[sizeof(uint32)+4]=m;
 			TIFFSeekFile(tif,sp->qtable_offset[m],SEEK_SET); 
-			p=(uint32)TIFFReadFile(tif,&ob[sizeof(uint32)+5],64);
+			p=TIFFReadFile(tif,&ob[sizeof(uint32)+5],64);
 			if (p!=64)
 				return(0);
 			sp->qtable[m]=ob;
@@ -1819,14 +1831,14 @@
 				}
 			}
 			TIFFSeekFile(tif,sp->dctable_offset[m],SEEK_SET);
-			p=(uint32)TIFFReadFile(tif,o,16);
+			p=TIFFReadFile(tif,o,16);
 			if (p!=16)
 				return(0);
 			q=0;
 			for (n=0; n<16; n++)
 				q+=o[n];
 			ra=sizeof(uint32)+21+q;
-			rb = (uint8*)_TIFFmalloc(ra);	// add (uint8*) cast
+			rb=_TIFFmalloc(ra);
 			if (rb==0)
 			{
 				TIFFErrorExt(tif->tif_clientdata,module,"Out of memory");
@@ -1840,7 +1852,7 @@
 			rb[sizeof(uint32)+4]=m;
 			for (n=0; n<16; n++)
 				rb[sizeof(uint32)+5+n]=o[n];
-			p=(uint32)TIFFReadFile(tif,&(rb[sizeof(uint32)+21]),q);
+			p=TIFFReadFile(tif,&(rb[sizeof(uint32)+21]),q);
 			if (p!=q)
 				return(0);
 			sp->dctable[m]=rb;
@@ -1883,14 +1895,14 @@
 				}
 			}
 			TIFFSeekFile(tif,sp->actable_offset[m],SEEK_SET);  
-			p=(uint32)TIFFReadFile(tif,o,16);
+			p=TIFFReadFile(tif,o,16);
 			if (p!=16)
 				return(0);
 			q=0;
 			for (n=0; n<16; n++)
 				q+=o[n];
 			ra=sizeof(uint32)+21+q;
-			rb = (uint8*)_TIFFmalloc(ra);	// add (uint8*) cast
+			rb=_TIFFmalloc(ra);
 			if (rb==0)
 			{
 				TIFFErrorExt(tif->tif_clientdata,module,"Out of memory");
@@ -1904,7 +1916,7 @@
 			rb[sizeof(uint32)+4]=(16|m);
 			for (n=0; n<16; n++)
 				rb[sizeof(uint32)+5+n]=o[n];
-			p=(uint32)TIFFReadFile(tif,&(rb[sizeof(uint32)+21]),q);
+			p=TIFFReadFile(tif,&(rb[sizeof(uint32)+21]),q);
 			if (p!=q)
 				return(0);
 			sp->actable[m]=rb;
@@ -1962,6 +1974,7 @@
 				break;
 			case osibsJpegInterchangeFormat:
 				sp->in_buffer_source=osibsStrile;
+                                break;
 			case osibsStrile:
 				if (!_TIFFFillStriles( sp->tif ) 
 				    || sp->tif->tif_dir.td_stripoffset == NULL
@@ -2059,7 +2072,7 @@
 	uint16 n;
 	assert(len>0);
 	mlen=len;
-	mmem = (uint8*)mem;		// add (uint8*) cast
+	mmem=mem;
 	do
 	{
 		if (sp->in_buffer_togo==0)
@@ -2461,8 +2474,8 @@
 		TIFFErrorExt(tif->tif_clientdata,"LibJpeg","Premature end of JPEG data");
 		jpeg_encap_unwind(tif);
 	}
-	sp->libjpeg_jpeg_source_mgr.bytes_in_buffer = len;
-	sp->libjpeg_jpeg_source_mgr.next_input_byte = (const JOCTET * )mem;		// add (const JOCTET * ) cast
+	sp->libjpeg_jpeg_source_mgr.bytes_in_buffer=len;
+	sp->libjpeg_jpeg_source_mgr.next_input_byte=mem;
 	return(1);
 }
 
@@ -2501,4 +2514,3 @@
  * fill-column: 78
  * End:
  */
-
diff --git a/third_party/tiff_v403/tif_open.c b/third_party/libtiff/tif_open.c
similarity index 99%
rename from third_party/tiff_v403/tif_open.c
rename to third_party/libtiff/tif_open.c
index f1c3e0a..8c88328 100644
--- a/third_party/tiff_v403/tif_open.c
+++ b/third_party/libtiff/tif_open.c
@@ -723,4 +723,3 @@
  * fill-column: 78
  * End:
  */
-
diff --git a/third_party/tiff_v403/tif_packbits.c b/third_party/libtiff/tif_packbits.c
similarity index 99%
rename from third_party/tiff_v403/tif_packbits.c
rename to third_party/libtiff/tif_packbits.c
index b599934..9e77190 100644
--- a/third_party/tiff_v403/tif_packbits.c
+++ b/third_party/libtiff/tif_packbits.c
@@ -23,6 +23,7 @@
  * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE 
  * OF THIS SOFTWARE.
  */
+
 #include "tiffiop.h"
 #ifdef PACKBITS_SUPPORT
 /*
@@ -297,4 +298,3 @@
  * fill-column: 78
  * End:
  */
-
diff --git a/third_party/tiff_v403/tif_pixarlog.c b/third_party/libtiff/tif_pixarlog.c
similarity index 98%
rename from third_party/tiff_v403/tif_pixarlog.c
rename to third_party/libtiff/tif_pixarlog.c
index b30e6d4..b93b4c7 100644
--- a/third_party/tiff_v403/tif_pixarlog.c
+++ b/third_party/libtiff/tif_pixarlog.c
@@ -1,4 +1,4 @@
-/* $Id: tif_pixarlog.c,v 1.38 2012-06-21 01:01:53 fwarmerdam Exp $ */
+/* $Id: tif_pixarlog.c,v 1.39 2012-12-10 17:27:13 tgl Exp $ */
 
 /*
  * Copyright (c) 1996-1997 Sam Leffler
@@ -23,6 +23,7 @@
  * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE 
  * OF THIS SOFTWARE.
  */
+
 #include "tiffiop.h"
 #ifdef PIXARLOG_SUPPORT
 
@@ -643,6 +644,20 @@
 	return bytes;
 }
 
+static tmsize_t
+add_ms(tmsize_t m1, tmsize_t m2)
+{
+	tmsize_t bytes = m1 + m2;
+
+	/* if either input is zero, assume overflow already occurred */
+	if (m1 == 0 || m2 == 0)
+		bytes = 0;
+	else if (bytes <= m1 || bytes <= m2)
+		bytes = 0;
+
+	return bytes;
+}
+
 static int
 PixarLogFixupTags(TIFF* tif)
 {
@@ -670,9 +685,11 @@
 	    td->td_samplesperpixel : 1);
 	tbuf_size = multiply_ms(multiply_ms(multiply_ms(sp->stride, td->td_imagewidth),
 				      td->td_rowsperstrip), sizeof(uint16));
+	/* add one more stride in case input ends mid-stride */
+	tbuf_size = add_ms(tbuf_size, sizeof(uint16) * sp->stride);
 	if (tbuf_size == 0)
 		return (0);   /* TODO: this is an error return without error report through TIFFErrorExt */
-	sp->tbuf = (uint16 *) _TIFFmalloc(tbuf_size+sizeof(uint16)*sp->stride);
+	sp->tbuf = (uint16 *) _TIFFmalloc(tbuf_size);
 	if (sp->tbuf == NULL)
 		return (0);
 	if (sp->user_datafmt == PIXARLOGDATAFMT_UNKNOWN)
@@ -905,7 +922,7 @@
 	    we need to simplify this code to reflect a ZLib that is likely updated
 	    to deal with 8byte memory sizes, though this code will respond
 	    apropriately even before we simplify it */
-	sp->stream.avail_out = (uInt)tif->tif_rawdatasize;
+	sp->stream.avail_out = tif->tif_rawdatasize;
 	if ((tmsize_t)sp->stream.avail_out != tif->tif_rawdatasize)
 	{
 		TIFFErrorExt(tif->tif_clientdata, module, "ZLib cannot deal with buffers this size");
@@ -1423,4 +1440,3 @@
  * fill-column: 78
  * End:
  */
-
diff --git a/third_party/tiff_v403/tif_predict.c b/third_party/libtiff/tif_predict.c
similarity index 82%
rename from third_party/tiff_v403/tif_predict.c
rename to third_party/libtiff/tif_predict.c
index a34faf0..1388dde 100644
--- a/third_party/tiff_v403/tif_predict.c
+++ b/third_party/libtiff/tif_predict.c
@@ -1,4 +1,4 @@
-/* $Id: tif_predict.c,v 1.32 2010-03-10 18:56:49 bfriesen Exp $ */
+/* $Id: tif_predict.c,v 1.35 2015-08-31 15:05:57 erouault Exp $ */
 
 /*
  * Copyright (c) 1988-1997 Sam Leffler
@@ -42,6 +42,8 @@
 static void horDiff8(TIFF* tif, uint8* cp0, tmsize_t cc);
 static void horDiff16(TIFF* tif, uint8* cp0, tmsize_t cc);
 static void horDiff32(TIFF* tif, uint8* cp0, tmsize_t cc);
+static void swabHorDiff16(TIFF* tif, uint8* cp0, tmsize_t cc);
+static void swabHorDiff32(TIFF* tif, uint8* cp0, tmsize_t cc);
 static void fpAcc(TIFF* tif, uint8* cp0, tmsize_t cc);
 static void fpDiff(TIFF* tif, uint8* cp0, tmsize_t cc);
 static int PredictorDecodeRow(TIFF* tif, uint8* op0, tmsize_t occ0, uint16 s);
@@ -207,7 +209,24 @@
                     sp->encodetile = tif->tif_encodetile;
                     tif->tif_encodetile = PredictorEncodeTile;
                 }
-	}
+
+                /*
+                 * If the data is horizontally differenced 16-bit data that
+                 * requires byte-swapping, then it must be byte swapped after
+                 * the differenciation step.  We do this with a special-purpose
+                 * routine and override the normal post decoding logic that
+                 * the library setup when the directory was read.
+                 */
+                if (tif->tif_flags & TIFF_SWAB) {
+                    if (sp->encodepfunc == horDiff16) {
+                            sp->encodepfunc = swabHorDiff16;
+                            tif->tif_postdecode = _TIFFNoPostDecode;
+                    } else if (sp->encodepfunc == horDiff32) {
+                            sp->encodepfunc = swabHorDiff32;
+                            tif->tif_postdecode = _TIFFNoPostDecode;
+                    }
+                }
+        }
 
 	else if (sp->predictor == 3) {
 		sp->encodepfunc = fpDiff;
@@ -239,18 +258,18 @@
     case 0:  ;			\
     }
 
+/* Remarks related to C standard compliance in all below functions : */
+/* - to avoid any undefined behaviour, we only operate on unsigned types */
+/*   since the behaviour of "overflows" is defined (wrap over) */
+/* - when storing into the byte stream, we explicitly mask with 0xff so */
+/*   as to make icc -check=conversions happy (not necessary by the standard) */
+
 static void
 horAcc8(TIFF* tif, uint8* cp0, tmsize_t cc)
 {
-	/*
-	 * compare v4.0.3 with v3.9.5, 
-	 * we find that horAcc8 uses while loop in the v4.0.3 and uses do while loop in the v3.9.5.
-	 * times of do while loop are less than while loop, so we use v3.9.5 instead of v4.0.3.
-	 */
-#if 0
 	tmsize_t stride = PredictorState(tif)->stride;
 
-	char* cp = (char*) cp0;
+	unsigned char* cp = (unsigned char*) cp0;
 	assert((cc%stride)==0);
 	if (cc > stride) {
 		/*
@@ -263,9 +282,9 @@
 			cc -= 3;
 			cp += 3;
 			while (cc>0) {
-				cp[0] = (char) (cr += cp[0]);
-				cp[1] = (char) (cg += cp[1]);
-				cp[2] = (char) (cb += cp[2]);
+				cp[0] = (unsigned char) ((cr += cp[0]) & 0xff);
+				cp[1] = (unsigned char) ((cg += cp[1]) & 0xff);
+				cp[2] = (unsigned char) ((cb += cp[2]) & 0xff);
 				cc -= 3;
 				cp += 3;
 			}
@@ -277,10 +296,10 @@
 			cc -= 4;
 			cp += 4;
 			while (cc>0) {
-				cp[0] = (char) (cr += cp[0]);
-				cp[1] = (char) (cg += cp[1]);
-				cp[2] = (char) (cb += cp[2]);
-				cp[3] = (char) (ca += cp[3]);
+				cp[0] = (unsigned char) ((cr += cp[0]) & 0xff);
+				cp[1] = (unsigned char) ((cg += cp[1]) & 0xff);
+				cp[2] = (unsigned char) ((cb += cp[2]) & 0xff);
+				cp[3] = (unsigned char) ((ca += cp[3]) & 0xff);
 				cc -= 4;
 				cp += 4;
 			}
@@ -288,70 +307,21 @@
 			cc -= stride;
 			do {
 				REPEAT4(stride, cp[stride] =
-					(char) (cp[stride] + *cp); cp++)
+					(unsigned char) ((cp[stride] + *cp) & 0xff); cp++)
 				cc -= stride;
 			} while (cc>0);
 		}
 	}
-#else
-	tsize_t stride = PredictorState(tif)->stride;
-
-	char* cp = (char*) cp0;
-	if (cc > stride) {
-		cc -= stride;
-		/*
-		 * Pipeline the most common cases.
-		 */
-		if (stride == 3)  {
-			unsigned int cr = cp[0];
-			unsigned int cg = cp[1];
-			unsigned int cb = cp[2];
-			do {
-				cc -= 3, cp += 3;
-				cp[0] = (char) (cr += cp[0]);
-				cp[1] = (char) (cg += cp[1]);
-				cp[2] = (char) (cb += cp[2]);
-			} while ((int32) cc > 0);
-		} else if (stride == 4)  {
-			unsigned int cr = cp[0];
-			unsigned int cg = cp[1];
-			unsigned int cb = cp[2];
-			unsigned int ca = cp[3];
-			do {
-				cc -= 4, cp += 4;
-				cp[0] = (char) (cr += cp[0]);
-				cp[1] = (char) (cg += cp[1]);
-				cp[2] = (char) (cb += cp[2]);
-				cp[3] = (char) (ca += cp[3]);
-			} while ((int32) cc > 0);
-		} else  {
-			do {
-				REPEAT4(stride, cp[stride] =
-					(char) (cp[stride] + *cp); cp++)
-				cc -= stride;
-			} while ((int32) cc > 0);
-		}
-	}
-#endif
 }
 
 static void
 swabHorAcc16(TIFF* tif, uint8* cp0, tmsize_t cc)
 {
-	tmsize_t stride = PredictorState(tif)->stride;
 	uint16* wp = (uint16*) cp0;
 	tmsize_t wc = cc / 2;
 
-	assert((cc%(2*stride))==0);
-
-	if (wc > stride) {
-		TIFFSwabArrayOfShort(wp, wc);
-		wc -= stride;
-		do {
-			REPEAT4(stride, wp[stride] += wp[0]; wp++)
-			wc -= stride;
-		} while (wc > 0);
-	}
+        TIFFSwabArrayOfShort(wp, wc);
+        horAcc16(tif, cp0, cc);
 }
 
 static void
@@ -366,7 +336,7 @@
 	if (wc > stride) {
 		wc -= stride;
 		do {
-			REPEAT4(stride, wp[stride] += wp[0]; wp++)
+			REPEAT4(stride, wp[stride] = (uint16)(((unsigned int)wp[stride] + (unsigned int)wp[0]) & 0xffff); wp++)
 			wc -= stride;
 		} while (wc > 0);
 	}
@@ -375,20 +345,11 @@
 static void
 swabHorAcc32(TIFF* tif, uint8* cp0, tmsize_t cc)
 {
-	tmsize_t stride = PredictorState(tif)->stride;
 	uint32* wp = (uint32*) cp0;
 	tmsize_t wc = cc / 4;
 
-	assert((cc%(4*stride))==0);
-
-	if (wc > stride) {
-		TIFFSwabArrayOfLong(wp, wc);
-		wc -= stride;
-		do {
-			REPEAT4(stride, wp[stride] += wp[0]; wp++)
-			wc -= stride;
-		} while (wc > 0);
-	}
+        TIFFSwabArrayOfLong(wp, wc);
+	horAcc32(tif, cp0, cc);
 }
 
 static void
@@ -428,7 +389,8 @@
 		return;
 
 	while (count > stride) {
-		REPEAT4(stride, cp[stride] += cp[0]; cp++)
+		REPEAT4(stride, cp[stride] =
+                        (unsigned char) ((cp[stride] + cp[0]) & 0xff); cp++)
 		count -= stride;
 	}
 
@@ -502,7 +464,7 @@
 {
 	TIFFPredictorState* sp = PredictorState(tif);
 	tmsize_t stride = sp->stride;
-	char* cp = (char*) cp0;
+	unsigned char* cp = (unsigned char*) cp0;
 
 	assert((cc%stride)==0);
 
@@ -512,33 +474,33 @@
 		 * Pipeline the most common cases.
 		 */
 		if (stride == 3) {
-			int r1, g1, b1;
-			int r2 = cp[0];
-			int g2 = cp[1];
-			int b2 = cp[2];
+			unsigned int r1, g1, b1;
+			unsigned int r2 = cp[0];
+			unsigned int g2 = cp[1];
+			unsigned  int b2 = cp[2];
 			do {
-				r1 = cp[3]; cp[3] = r1-r2; r2 = r1;
-				g1 = cp[4]; cp[4] = g1-g2; g2 = g1;
-				b1 = cp[5]; cp[5] = b1-b2; b2 = b1;
+				r1 = cp[3]; cp[3] = (unsigned char)((r1-r2)&0xff); r2 = r1;
+				g1 = cp[4]; cp[4] = (unsigned char)((g1-g2)&0xff); g2 = g1;
+				b1 = cp[5]; cp[5] = (unsigned char)((b1-b2)&0xff); b2 = b1;
 				cp += 3;
 			} while ((cc -= 3) > 0);
 		} else if (stride == 4) {
-			int r1, g1, b1, a1;
-			int r2 = cp[0];
-			int g2 = cp[1];
-			int b2 = cp[2];
-			int a2 = cp[3];
+			unsigned int r1, g1, b1, a1;
+			unsigned int r2 = cp[0];
+			unsigned int g2 = cp[1];
+			unsigned int b2 = cp[2];
+			unsigned int a2 = cp[3];
 			do {
-				r1 = cp[4]; cp[4] = r1-r2; r2 = r1;
-				g1 = cp[5]; cp[5] = g1-g2; g2 = g1;
-				b1 = cp[6]; cp[6] = b1-b2; b2 = b1;
-				a1 = cp[7]; cp[7] = a1-a2; a2 = a1;
+				r1 = cp[4]; cp[4] = (unsigned char)((r1-r2)&0xff); r2 = r1;
+				g1 = cp[5]; cp[5] = (unsigned char)((g1-g2)&0xff); g2 = g1;
+				b1 = cp[6]; cp[6] = (unsigned char)((b1-b2)&0xff); b2 = b1;
+				a1 = cp[7]; cp[7] = (unsigned char)((a1-a2)&0xff); a2 = a1;
 				cp += 4;
 			} while ((cc -= 4) > 0);
 		} else {
 			cp += cc - 1;
 			do {
-				REPEAT4(stride, cp[stride] -= cp[0]; cp--)
+				REPEAT4(stride, cp[stride] = (unsigned char)((cp[stride] - cp[0])&0xff); cp--)
 			} while ((cc -= stride) > 0);
 		}
 	}
@@ -549,7 +511,7 @@
 {
 	TIFFPredictorState* sp = PredictorState(tif);
 	tmsize_t stride = sp->stride;
-	int16 *wp = (int16*) cp0;
+	uint16 *wp = (uint16*) cp0;
 	tmsize_t wc = cc/2;
 
 	assert((cc%(2*stride))==0);
@@ -558,18 +520,29 @@
 		wc -= stride;
 		wp += wc - 1;
 		do {
-			REPEAT4(stride, wp[stride] -= wp[0]; wp--)
+			REPEAT4(stride, wp[stride] = (uint16)(((unsigned int)wp[stride] - (unsigned int)wp[0]) & 0xffff); wp--)
 			wc -= stride;
 		} while (wc > 0);
 	}
 }
 
 static void
+swabHorDiff16(TIFF* tif, uint8* cp0, tmsize_t cc)
+{
+    uint16* wp = (uint16*) cp0;
+    tmsize_t wc = cc / 2;
+
+    horDiff16(tif, cp0, cc);
+
+    TIFFSwabArrayOfShort(wp, wc);
+}
+
+static void
 horDiff32(TIFF* tif, uint8* cp0, tmsize_t cc)
 {
 	TIFFPredictorState* sp = PredictorState(tif);
 	tmsize_t stride = sp->stride;
-	int32 *wp = (int32*) cp0;
+	uint32 *wp = (uint32*) cp0;
 	tmsize_t wc = cc/4;
 
 	assert((cc%(4*stride))==0);
@@ -584,6 +557,17 @@
 	}
 }
 
+static void
+swabHorDiff32(TIFF* tif, uint8* cp0, tmsize_t cc)
+{
+    uint32* wp = (uint32*) cp0;
+    tmsize_t wc = cc / 4;
+
+    horDiff32(tif, cp0, cc);
+
+    TIFFSwabArrayOfLong(wp, wc);
+}
+
 /*
  * Floating point predictor differencing routine.
  */
@@ -619,7 +603,7 @@
 	cp = (uint8 *) cp0;
 	cp += cc - stride - 1;
 	for (count = cc; count > stride; count -= stride)
-		REPEAT4(stride, cp[stride] -= cp[0]; cp--)
+		REPEAT4(stride, cp[stride] = (unsigned char)((cp[stride] - cp[0])&0xff); cp--)
 }
 
 static int
@@ -808,4 +792,3 @@
  * fill-column: 78
  * End:
  */
-
diff --git a/third_party/tiff_v403/tif_predict.h b/third_party/libtiff/tif_predict.h
similarity index 100%
rename from third_party/tiff_v403/tif_predict.h
rename to third_party/libtiff/tif_predict.h
diff --git a/third_party/tiff_v403/tif_print.c b/third_party/libtiff/tif_print.c
similarity index 97%
rename from third_party/tiff_v403/tif_print.c
rename to third_party/libtiff/tif_print.c
index f93e557..7b1a422 100644
--- a/third_party/tiff_v403/tif_print.c
+++ b/third_party/libtiff/tif_print.c
@@ -1,4 +1,4 @@
-/* $Id: tif_print.c,v 1.60 2012-08-19 16:56:35 bfriesen Exp $ */
+/* $Id: tif_print.c,v 1.62 2015-08-19 02:31:04 bfriesen Exp $ */
 
 /*
  * Copyright (c) 1988-1997 Sam Leffler
@@ -35,7 +35,7 @@
 #include <ctype.h>
 
 static void
-_TIFFprintAsciiBounded(FILE* fd, const char* cp, int max_chars);
+_TIFFprintAsciiBounded(FILE* fd, const char* cp, size_t max_chars);
 
 static const char *photoNames[] = {
     "min-is-white",				/* PHOTOMETRIC_MINISWHITE */
@@ -395,8 +395,8 @@
 		for (cp = td->td_inknames; 
 		     i > 0 && cp < td->td_inknames + td->td_inknameslen; 
 		     cp = strchr(cp,'\0')+1, i--) {
-			int max_chars = 
-				(int)(td->td_inknameslen - (cp - td->td_inknames));
+			size_t max_chars = 
+				td->td_inknameslen - (cp - td->td_inknames);
 			fputs(sep, fd);
 			_TIFFprintAsciiBounded(fd, cp, max_chars);
 			sep = ", ";
@@ -582,10 +582,10 @@
 				continue;
 
 			if(fip->field_passcount) {
-				if (fip->field_readcount == TIFF_VARIABLE ) {
+				if (fip->field_readcount == TIFF_VARIABLE2 ) {
 					if(TIFFGetField(tif, tag, &value_count, &raw_data) != 1)
 						continue;
-				} else if (fip->field_readcount == TIFF_VARIABLE2 ) {
+				} else if (fip->field_readcount == TIFF_VARIABLE ) {
 					uint16 small_value_count;
 					if(TIFFGetField(tif, tag, &small_value_count, &raw_data) != 1)
 						continue;
@@ -675,11 +675,11 @@
 void
 _TIFFprintAscii(FILE* fd, const char* cp)
 {
-	_TIFFprintAsciiBounded( fd, cp, (int)strlen(cp));
+	_TIFFprintAsciiBounded( fd, cp, strlen(cp));
 }
 
 static void
-_TIFFprintAsciiBounded(FILE* fd, const char* cp, int max_chars)
+_TIFFprintAsciiBounded(FILE* fd, const char* cp, size_t max_chars)
 {
 	for (; max_chars > 0 && *cp != '\0'; cp++, max_chars--) {
 		const char* tp;
@@ -714,4 +714,3 @@
  * fill-column: 78
  * End:
  */
-
diff --git a/third_party/tiff_v403/tif_read.c b/third_party/libtiff/tif_read.c
similarity index 94%
rename from third_party/tiff_v403/tif_read.c
rename to third_party/libtiff/tif_read.c
index eb93508..5cb419b 100644
--- a/third_party/tiff_v403/tif_read.c
+++ b/third_party/libtiff/tif_read.c
@@ -1,4 +1,4 @@
-/* $Id: tif_read.c,v 1.41 2012-07-06 19:22:58 bfriesen Exp $ */
+/* $Id: tif_read.c,v 1.45 2015-06-07 22:35:40 bfriesen Exp $ */
 
 /*
  * Copyright (c) 1988-1997 Sam Leffler
@@ -47,7 +47,7 @@
 {
 	static const char module[] = "TIFFFillStripPartial";
 	register TIFFDirectory *td = &tif->tif_dir;
-        uint64 unused_data;
+        tmsize_t unused_data;
         uint64 read_offset;
         tmsize_t cc, to_read;
         /* tmsize_t bytecountm; */
@@ -94,7 +94,7 @@
         if( unused_data > 0 )
         {
 		assert((tif->tif_flags&TIFF_BUFFERMMAP)==0);
-                memmove( tif->tif_rawdata, tif->tif_rawcp, (size_t)unused_data );
+                memmove( tif->tif_rawdata, tif->tif_rawcp, unused_data );
         }
 
         /*
@@ -113,12 +113,12 @@
         /*
         ** How much do we want to read?
         */
-        to_read = (tmsize_t)(tif->tif_rawdatasize - unused_data);
+        to_read = tif->tif_rawdatasize - unused_data;
         if( (uint64) to_read > td->td_stripbytecount[strip] 
             - tif->tif_rawdataoff - tif->tif_rawdataloaded )
         {
-                to_read = (tmsize_t)(td->td_stripbytecount[strip]
-                        - tif->tif_rawdataoff - tif->tif_rawdataloaded);
+                to_read = (tmsize_t) td->td_stripbytecount[strip]
+                        - tif->tif_rawdataoff - tif->tif_rawdataloaded;
         }
 
 	assert((tif->tif_flags&TIFF_BUFFERMMAP)==0);
@@ -141,8 +141,8 @@
                 return 0;
         }
         
-        tif->tif_rawdataoff = (tmsize_t)(tif->tif_rawdataoff + tif->tif_rawdataloaded - unused_data) ;
-        tif->tif_rawdataloaded = (tmsize_t)unused_data + to_read;
+        tif->tif_rawdataoff = tif->tif_rawdataoff + tif->tif_rawdataloaded - unused_data ;
+        tif->tif_rawdataloaded = unused_data + to_read;
 
         tif->tif_rawcp = tif->tif_rawdata;
                         
@@ -321,7 +321,7 @@
 	uint32 rowsperstrip;
 	uint32 stripsperplane;
 	uint32 stripinplane;
-	uint16 plane, comp;
+	uint16 plane;
 	uint32 rows;
 	tmsize_t stripsize;
 	if (!TIFFCheckRead(tif,0))
@@ -352,42 +352,12 @@
 		return((tmsize_t)(-1));
 	if ((size!=(tmsize_t)(-1))&&(size<stripsize))
 		stripsize=size;
-
-	/*
-	 * discard those.
-	 * keep code modified by Changjin Gao.
-	 * Xiaochuan Liu 20100828.
-	 */
-	/*if (!TIFFFillStrip(tif,strip))
+	if (!TIFFFillStrip(tif,strip))
 		return((tmsize_t)(-1));
 	if ((*tif->tif_decodestrip)(tif,buf,stripsize,plane)<=0)
 		return((tmsize_t)(-1));
 	(*tif->tif_postdecode)(tif,buf,stripsize);
-	return(stripsize);*/
-	
-	/*
-	* Changjin Gao 20110726 fixed decode error issue.
-	* Test file: mantis #27308 020511-1158450.tiff.
-	*/
-	comp = COMPRESSION_NONE;
-StripDecode:
-	if (TIFFFillStrip(tif, strip) && (*tif->tif_decodestrip)(tif, buf, stripsize, plane) > 0)
-	{
-		(*tif->tif_postdecode)(tif, buf, stripsize);
-		return (stripsize);
-	}
-	else
-	{
-		if (comp < 9)
-		{
-			TIFFSetField(tif, TIFFTAG_COMPRESSION, comp);
-			TIFFSetField(tif, TIFFTAG_FAXMODE,FAXMODE_CLASSIC);
-			comp++;
-			goto StripDecode;
-		}
-
-		return ((tsize_t) -1);
-	}
+	return(stripsize);
 }
 
 static tmsize_t
@@ -488,7 +458,7 @@
 		return ((tmsize_t)(-1));
 	}
 	bytecount = td->td_stripbytecount[strip];
-	if (bytecount <= 0) {
+	if ((int64)bytecount <= 0) {
 #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__))
 		TIFFErrorExt(tif->tif_clientdata, module,
 			     "%I64u: Invalid strip byte count, strip %lu",
@@ -528,7 +498,7 @@
 	if ((tif->tif_flags&TIFF_NOREADRAW)==0)
 	{
 		uint64 bytecount = td->td_stripbytecount[strip];
-		if (bytecount <= 0) {
+		if ((int64)bytecount <= 0) {
 #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__))
 			TIFFErrorExt(tif->tif_clientdata, module,
 				"Invalid strip byte count %I64u, strip %lu",
@@ -831,7 +801,7 @@
 	if ((tif->tif_flags&TIFF_NOREADRAW)==0)
 	{
 		uint64 bytecount = td->td_stripbytecount[tile];
-		if (bytecount <= 0) {
+		if ((int64)bytecount <= 0) {
 #if defined(__WIN32__) && (defined(_MSC_VER) || defined(__MINGW32__))
 			TIFFErrorExt(tif->tif_clientdata, module,
 				"%I64u: Invalid tile byte count, tile %lu",
@@ -960,8 +930,11 @@
 		tif->tif_flags &= ~TIFF_MYBUFFER;
 	} else {
 		tif->tif_rawdatasize = (tmsize_t)TIFFroundup_64((uint64)size, 1024);
-		if (tif->tif_rawdatasize==0)
-			tif->tif_rawdatasize=(tmsize_t)(-1);
+		if (tif->tif_rawdatasize==0) {
+		    TIFFErrorExt(tif->tif_clientdata, module,
+				 "Invalid buffer size");
+		    return (0);
+		}
 		tif->tif_rawdata = (uint8*) _TIFFmalloc(tif->tif_rawdatasize);
 		tif->tif_flags |= TIFF_MYBUFFER;
 	}
@@ -1017,10 +990,12 @@
 static int
 TIFFStartTile(TIFF* tif, uint32 tile)
 {
+        static const char module[] = "TIFFStartTile";
 	TIFFDirectory *td = &tif->tif_dir;
+        uint32 howmany32;
 
-    if (!_TIFFFillStriles( tif ) || !tif->tif_dir.td_stripbytecount)
-        return 0;
+        if (!_TIFFFillStriles( tif ) || !tif->tif_dir.td_stripbytecount)
+                return 0;
 
 	if ((tif->tif_flags & TIFF_CODERSETUP) == 0) {
 		if (!(*tif->tif_setupdecode)(tif))
@@ -1028,12 +1003,18 @@
 		tif->tif_flags |= TIFF_CODERSETUP;
 	}
 	tif->tif_curtile = tile;
-	tif->tif_row =
-	    (tile % TIFFhowmany_32(td->td_imagewidth, td->td_tilewidth)) *
-		td->td_tilelength;
-	tif->tif_col =
-	    (tile % TIFFhowmany_32(td->td_imagelength, td->td_tilelength)) *
-		td->td_tilewidth;
+        howmany32=TIFFhowmany_32(td->td_imagewidth, td->td_tilewidth);
+        if (howmany32 == 0) {
+                 TIFFErrorExt(tif->tif_clientdata,module,"Zero tiles");
+                return 0;
+        }
+	tif->tif_row = (tile % howmany32) * td->td_tilelength;
+        howmany32=TIFFhowmany_32(td->td_imagelength, td->td_tilelength);
+        if (howmany32 == 0) {
+                TIFFErrorExt(tif->tif_clientdata,module,"Zero tiles");
+                return 0;
+        }
+	tif->tif_col = (tile % howmany32) * td->td_tilewidth;
         tif->tif_flags &= ~TIFF_BUF4WRITE;
 	if (tif->tif_flags&TIFF_NOREADRAW)
 	{
@@ -1111,4 +1092,3 @@
  * fill-column: 78
  * End:
  */
-
diff --git a/third_party/tiff_v403/tif_strip.c b/third_party/libtiff/tif_strip.c
similarity index 97%
rename from third_party/tiff_v403/tif_strip.c
rename to third_party/libtiff/tif_strip.c
index 2c15a70..6cac71d 100644
--- a/third_party/tiff_v403/tif_strip.c
+++ b/third_party/libtiff/tif_strip.c
@@ -1,4 +1,4 @@
-/* $Id: tif_strip.c,v 1.35 2012-06-06 05:33:55 fwarmerdam Exp $ */
+/* $Id: tif_strip.c,v 1.36 2015-06-07 22:35:40 bfriesen Exp $ */
 
 /*
  * Copyright (c) 1991-1997 Sam Leffler
@@ -317,7 +317,14 @@
 		}
 	}
 	else
+        {
 		scanline_size=TIFFhowmany_64(_TIFFMultiply64(tif,td->td_imagewidth,td->td_bitspersample,module),8);
+        }
+        if (scanline_size == 0)
+        {
+                TIFFErrorExt(tif->tif_clientdata,module,"Computed scanline size is zero");
+                return 0;
+        }
 	return(scanline_size);
 }
 tmsize_t
@@ -328,8 +335,7 @@
 	tmsize_t n;
 	m=TIFFScanlineSize64(tif);
 	n=(tmsize_t)m;
-	if ((uint64)n!=m)
-	{
+	if ((uint64)n!=m) {
 		TIFFErrorExt(tif->tif_clientdata,module,"Integer arithmetic overflow");
 		n=0;
 	}
@@ -381,4 +387,3 @@
  * fill-column: 78
  * End:
  */
-
diff --git a/third_party/tiff_v403/tif_swab.c b/third_party/libtiff/tif_swab.c
similarity index 99%
rename from third_party/tiff_v403/tif_swab.c
rename to third_party/libtiff/tif_swab.c
index 205e529..f37e33f 100644
--- a/third_party/tiff_v403/tif_swab.c
+++ b/third_party/libtiff/tif_swab.c
@@ -308,4 +308,3 @@
  * fill-column: 78
  * End:
  */
-
diff --git a/third_party/tiff_v403/tif_thunder.c b/third_party/libtiff/tif_thunder.c
similarity index 99%
rename from third_party/tiff_v403/tif_thunder.c
rename to third_party/libtiff/tif_thunder.c
index e2d4ac0..390891c 100644
--- a/third_party/tiff_v403/tif_thunder.c
+++ b/third_party/libtiff/tif_thunder.c
@@ -23,6 +23,7 @@
  * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE 
  * OF THIS SOFTWARE.
  */
+
 #include "tiffiop.h"
 #include <assert.h>
 #ifdef THUNDER_SUPPORT
@@ -204,5 +205,3 @@
  * fill-column: 78
  * End:
  */
-
-
diff --git a/third_party/tiff_v403/tif_tile.c b/third_party/libtiff/tif_tile.c
similarity index 89%
rename from third_party/tiff_v403/tif_tile.c
rename to third_party/libtiff/tif_tile.c
index cb59a59..388e168 100644
--- a/third_party/tiff_v403/tif_tile.c
+++ b/third_party/libtiff/tif_tile.c
@@ -1,4 +1,4 @@
-/* $Id: tif_tile.c,v 1.23 2012-06-06 05:33:55 fwarmerdam Exp $ */
+/* $Id: tif_tile.c,v 1.24 2015-06-07 22:35:40 bfriesen Exp $ */
 
 /*
  * Copyright (c) 1991-1997 Sam Leffler
@@ -143,17 +143,40 @@
 uint64
 TIFFTileRowSize64(TIFF* tif)
 {
+        static const char module[] = "TIFFTileRowSize64";
 	TIFFDirectory *td = &tif->tif_dir;
 	uint64 rowsize;
+	uint64 tilerowsize;
 
-	if (td->td_tilelength == 0 || td->td_tilewidth == 0)
+	if (td->td_tilelength == 0)
+        {
+                TIFFErrorExt(tif->tif_clientdata,module,"Tile length is zero");
+                return 0;
+        }
+        if (td->td_tilewidth == 0)
+        {
+                TIFFErrorExt(tif->tif_clientdata,module,"Tile width is zero");
 		return (0);
+        }
 	rowsize = _TIFFMultiply64(tif, td->td_bitspersample, td->td_tilewidth,
 	    "TIFFTileRowSize");
 	if (td->td_planarconfig == PLANARCONFIG_CONTIG)
+        {
+                if (td->td_samplesperpixel == 0)
+                {
+                        TIFFErrorExt(tif->tif_clientdata,module,"Samples per pixel is zero");
+                        return 0;
+                }
 		rowsize = _TIFFMultiply64(tif, rowsize, td->td_samplesperpixel,
 		    "TIFFTileRowSize");
-	return (TIFFhowmany8_64(rowsize));
+        }
+        tilerowsize=TIFFhowmany8_64(rowsize);
+        if (tilerowsize == 0)
+        {
+                TIFFErrorExt(tif->tif_clientdata,module,"Computed tile row size is zero");
+                return 0;
+        }
+	return (tilerowsize);
 }
 tmsize_t
 TIFFTileRowSize(TIFF* tif)
@@ -297,4 +320,3 @@
  * fill-column: 78
  * End:
  */
-
diff --git a/third_party/tiff_v403/tif_version.c b/third_party/libtiff/tif_version.c
similarity index 99%
rename from third_party/tiff_v403/tif_version.c
rename to third_party/libtiff/tif_version.c
index 30119d2..f92c843 100644
--- a/third_party/tiff_v403/tif_version.c
+++ b/third_party/libtiff/tif_version.c
@@ -38,4 +38,3 @@
  * fill-column: 78
  * End:
  */
-
diff --git a/third_party/tiff_v403/tif_warning.c b/third_party/libtiff/tif_warning.c
similarity index 92%
rename from third_party/tiff_v403/tif_warning.c
rename to third_party/libtiff/tif_warning.c
index 997f353..423b636 100644
--- a/third_party/tiff_v403/tif_warning.c
+++ b/third_party/libtiff/tif_warning.c
@@ -29,9 +29,7 @@
  */
 #include "tiffiop.h"
 
-/*TIFFErrorHandlerExt _TIFFwarningHandlerExt = NULL;*/
-/* Modify here for use _TIFFwarningHandlerExt by Sunliang.Liu 20090715 */
-TIFFErrorHandler _TIFFwarningHandler = NULL;
+TIFFErrorHandlerExt _TIFFwarningHandlerExt = NULL;
 
 TIFFErrorHandler
 TIFFSetWarningHandler(TIFFErrorHandler handler)
@@ -81,5 +79,3 @@
  * fill-column: 78
  * End:
  */
-
-
diff --git a/third_party/tiff_v403/tif_write.c b/third_party/libtiff/tif_write.c
similarity index 94%
rename from third_party/tiff_v403/tif_write.c
rename to third_party/libtiff/tif_write.c
index f32ee90..7996c31 100644
--- a/third_party/tiff_v403/tif_write.c
+++ b/third_party/libtiff/tif_write.c
@@ -1,4 +1,4 @@
-/* $Id: tif_write.c,v 1.37 2012-08-13 22:10:17 fwarmerdam Exp $ */
+/* $Id: tif_write.c,v 1.42 2015-06-07 23:00:23 bfriesen Exp $ */
 
 /*
  * Copyright (c) 1988-1997 Sam Leffler
@@ -115,6 +115,10 @@
 		if (strip >= td->td_stripsperimage && imagegrew)
 			td->td_stripsperimage =
 			    TIFFhowmany_32(td->td_imagelength,td->td_rowsperstrip);
+                if (td->td_stripsperimage == 0) {
+                        TIFFErrorExt(tif->tif_clientdata, module, "Zero strips per image");
+                        return (-1);
+                }
 		tif->tif_row =
 		    (strip % td->td_stripsperimage) * td->td_rowsperstrip;
 		if ((tif->tif_flags & TIFF_CODERSETUP) == 0) {
@@ -220,6 +224,11 @@
         tif->tif_flags |= TIFF_BUF4WRITE;
 	tif->tif_curstrip = strip;
 
+        if (td->td_stripsperimage == 0) {
+                TIFFErrorExt(tif->tif_clientdata, module, "Zero strips per image");
+                return ((tmsize_t) -1);
+        }
+
 	tif->tif_row = (strip % td->td_stripsperimage) * td->td_rowsperstrip;
 	if ((tif->tif_flags & TIFF_CODERSETUP) == 0) {
 		if (!(*tif->tif_setupencode)(tif))
@@ -311,6 +320,10 @@
 			return ((tmsize_t) -1);
 	}
 	tif->tif_curstrip = strip;
+        if (td->td_stripsperimage == 0) {
+                TIFFErrorExt(tif->tif_clientdata, module,"Zero strips per image");
+                return ((tmsize_t) -1);
+        }
 	tif->tif_row = (strip % td->td_stripsperimage) * td->td_rowsperstrip;
 	return (TIFFAppendToStrip(tif, strip, (uint8*) data, cc) ?
 	    cc : (tmsize_t) -1);
@@ -353,6 +366,7 @@
 	static const char module[] = "TIFFWriteEncodedTile";
 	TIFFDirectory *td;
 	uint16 sample;
+        uint32 howmany32;
 
 	if (!WRITECHECKTILES(tif, module))
 		return ((tmsize_t)(-1));
@@ -379,7 +393,7 @@
             /* more bytes available in the output buffer than the previous byte count, */
             /* so that TIFFAppendToStrip() will detect the overflow when it is called the first */
             /* time if the new compressed tile is bigger than the older one. (GDAL #4771) */
-            if( tif->tif_rawdatasize <= (tmsize_t)td->td_stripbytecount[tile] )
+            if( tif->tif_rawdatasize <= (tmsize_t) td->td_stripbytecount[tile] )
             {
                 if( !(TIFFWriteBufferSetup(tif, NULL,
                     (tmsize_t)TIFFroundup_64((uint64)(td->td_stripbytecount[tile] + 1), 1024))) )
@@ -391,17 +405,25 @@
             tif->tif_curoff = 0;
         }
 
-    tif->tif_rawcc = 0;
-    tif->tif_rawcp = tif->tif_rawdata;
+	tif->tif_rawcc = 0;
+	tif->tif_rawcp = tif->tif_rawdata;
 
 	/* 
 	 * Compute tiles per row & per column to compute
 	 * current row and column
 	 */
-	tif->tif_row = (tile % TIFFhowmany_32(td->td_imagelength, td->td_tilelength))
-		* td->td_tilelength;
-	tif->tif_col = (tile % TIFFhowmany_32(td->td_imagewidth, td->td_tilewidth))
-		* td->td_tilewidth;
+        howmany32=TIFFhowmany_32(td->td_imagelength, td->td_tilelength);
+        if (howmany32 == 0) {
+                 TIFFErrorExt(tif->tif_clientdata,module,"Zero tiles");
+                return ((tmsize_t)(-1));
+        }
+	tif->tif_row = (tile % howmany32) * td->td_tilelength;
+        howmany32=TIFFhowmany_32(td->td_imagewidth, td->td_tilewidth);
+        if (howmany32 == 0) {
+                 TIFFErrorExt(tif->tif_clientdata,module,"Zero tiles");
+                return ((tmsize_t)(-1));
+        }
+	tif->tif_col = (tile % howmany32) * td->td_tilewidth;
 
 	if ((tif->tif_flags & TIFF_CODERSETUP) == 0) {
 		if (!(*tif->tif_setupencode)(tif))
@@ -769,4 +791,3 @@
  * fill-column: 78
  * End:
  */
-
diff --git a/third_party/tiff_v403/tif_zip.c b/third_party/libtiff/tif_zip.c
similarity index 94%
rename from third_party/tiff_v403/tif_zip.c
rename to third_party/libtiff/tif_zip.c
index 1a0d821..b3ac9b9 100644
--- a/third_party/tiff_v403/tif_zip.c
+++ b/third_party/libtiff/tif_zip.c
@@ -1,4 +1,4 @@
-/* $Id: tif_zip.c,v 1.31 2011-01-06 16:00:23 fwarmerdam Exp $ */
+/* $Id: tif_zip.c,v 1.33 2014-12-25 18:29:11 erouault Exp $ */
 
 /*
  * Copyright (c) 1995-1997 Sam Leffler
@@ -23,6 +23,7 @@
  * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE 
  * OF THIS SOFTWARE.
  */
+
 #include "tiffiop.h"
 #ifdef ZIP_SUPPORT
 /*
@@ -35,7 +36,7 @@
  * of the library: this code assumes the 1.0 API and also depends on
  * the ability to write the zlib header multiple times (one per strip)
  * which was not possible with versions prior to 0.95.  Note also that
- * older versions of this codec avoided this bug by supressing the header
+ * older versions of this codec avoided this bug by suppressing the header
  * entirely.  This means that files written with the old library cannot
  * be read; they should be converted to a different compression scheme
  * and then reconverted.
@@ -60,6 +61,8 @@
 #error "Antiquated ZLIB software; you must use version 1.0 or later"
 #endif
 
+#define SAFE_MSG(sp)   ((sp)->stream.msg == NULL ? "" : (sp)->stream.msg)
+
 /*
  * State block for each open TIFF
  * file using ZIP compression/decompression.
@@ -105,7 +108,7 @@
 	}
 
 	if (inflateInit(&sp->stream) != Z_OK) {
-		TIFFErrorExt(tif->tif_clientdata, module, "%s", sp->stream.msg);
+		TIFFErrorExt(tif->tif_clientdata, module, "%s", SAFE_MSG(sp));
 		return (0);
 	} else {
 		sp->state |= ZSTATE_INIT_DECODE;
@@ -173,14 +176,14 @@
 		if (state == Z_DATA_ERROR) {
 			TIFFErrorExt(tif->tif_clientdata, module,
 			    "Decoding error at scanline %lu, %s",
-			    (unsigned long) tif->tif_row, sp->stream.msg);
+			     (unsigned long) tif->tif_row, SAFE_MSG(sp));
 			if (inflateSync(&sp->stream) != Z_OK)
 				return (0);
 			continue;
 		}
 		if (state != Z_OK) {
-			TIFFErrorExt(tif->tif_clientdata, module, "ZLib error: %s",
-			    sp->stream.msg);
+			TIFFErrorExt(tif->tif_clientdata, module, 
+				     "ZLib error: %s", SAFE_MSG(sp));
 			return (0);
 		}
 	} while (sp->stream.avail_out > 0);
@@ -210,7 +213,7 @@
 	}
 
 	if (deflateInit(&sp->stream, sp->zipquality) != Z_OK) {
-		TIFFErrorExt(tif->tif_clientdata, module, "%s", sp->stream.msg);
+		TIFFErrorExt(tif->tif_clientdata, module, "%s", SAFE_MSG(sp));
 		return (0);
 	} else {
 		sp->state |= ZSTATE_INIT_ENCODE;
@@ -237,7 +240,7 @@
 	    we need to simplify this code to reflect a ZLib that is likely updated
 	    to deal with 8byte memory sizes, though this code will respond
 	    apropriately even before we simplify it */
-	sp->stream.avail_out = (uInt)tif->tif_rawdatasize;
+	sp->stream.avail_out = tif->tif_rawdatasize;
 	if ((tmsize_t)sp->stream.avail_out != tif->tif_rawdatasize)
 	{
 		TIFFErrorExt(tif->tif_clientdata, module, "ZLib cannot deal with buffers this size");
@@ -272,8 +275,9 @@
 	}
 	do {
 		if (deflate(&sp->stream, Z_NO_FLUSH) != Z_OK) {
-			TIFFErrorExt(tif->tif_clientdata, module, "Encoder error: %s",
-			    sp->stream.msg);
+			TIFFErrorExt(tif->tif_clientdata, module, 
+				     "Encoder error: %s",
+				     SAFE_MSG(sp));
 			return (0);
 		}
 		if (sp->stream.avail_out == 0) {
@@ -312,8 +316,8 @@
 			}
 			break;
 		default:
-			TIFFErrorExt(tif->tif_clientdata, module, "ZLib error: %s",
-			    sp->stream.msg);
+			TIFFErrorExt(tif->tif_clientdata, module, 
+				     "ZLib error: %s", SAFE_MSG(sp));
 			return (0);
 		}
 	} while (state != Z_STREAM_END);
@@ -358,7 +362,7 @@
 			if (deflateParams(&sp->stream,
 			    sp->zipquality, Z_DEFAULT_STRATEGY) != Z_OK) {
 				TIFFErrorExt(tif->tif_clientdata, module, "ZLib error: %s",
-				    sp->stream.msg);
+					     SAFE_MSG(sp));
 				return (0);
 			}
 		}
@@ -466,4 +470,3 @@
  * fill-column: 78
  * End:
  */
-
diff --git a/third_party/tiff_v403/tiff.h b/third_party/libtiff/tiff.h
similarity index 98%
rename from third_party/tiff_v403/tiff.h
rename to third_party/libtiff/tiff.h
index 19b4e79..bc46acd 100644
--- a/third_party/tiff_v403/tiff.h
+++ b/third_party/libtiff/tiff.h
@@ -1,4 +1,4 @@
-/* $Id: tiff.h,v 1.68 2012-08-19 16:56:35 bfriesen Exp $ */
+/* $Id: tiff.h,v 1.69 2014-04-02 17:23:06 fwarmerdam Exp $ */
 
 /*
  * Copyright (c) 1988-1997 Sam Leffler
@@ -201,6 +201,7 @@
 #define	    PHOTOMETRIC_CIELAB		8	/* !1976 CIE L*a*b* */
 #define	    PHOTOMETRIC_ICCLAB		9	/* ICC L*a*b* [Adobe TIFF Technote 4] */
 #define	    PHOTOMETRIC_ITULAB		10	/* ITU L*a*b* */
+#define	    PHOTOMETRIC_CFA		32803	/* color filter array */
 #define     PHOTOMETRIC_LOGL		32844	/* CIE Log2(L) */
 #define     PHOTOMETRIC_LOGLUV		32845	/* CIE Log2(L) (u',v') */
 #define	TIFFTAG_THRESHHOLDING		263	/* +thresholding used on data */
@@ -402,6 +403,8 @@
 #define TIFFTAG_PIXAR_MATRIX_WORLDTOCAMERA 33306
 /* tag 33405 is a private tag registered to Eastman Kodak */
 #define TIFFTAG_WRITERSERIALNUMBER      33405   /* device serial number */
+#define TIFFTAG_CFAREPEATPATTERNDIM	33421	/* dimensions of CFA pattern */
+#define TIFFTAG_CFAPATTERN		33422	/* color filter array pattern */
 /* tag 33432 is listed in the 6.0 spec w/ unknown ownership */
 #define	TIFFTAG_COPYRIGHT		33432	/* copyright string */
 /* IPTC TAG from RichTIFF specifications */
diff --git a/third_party/tiff_v403/tiffconf.h b/third_party/libtiff/tiffconf.h
similarity index 99%
rename from third_party/tiff_v403/tiffconf.h
rename to third_party/libtiff/tiffconf.h
index e36bde6..fab7e0d 100644
--- a/third_party/tiff_v403/tiffconf.h
+++ b/third_party/libtiff/tiffconf.h
@@ -57,6 +57,8 @@
 #define SIZEOF_UNSIGNED_LONG 4
 #endif
 
+#define HAVE_SNPRINTF 1
+
 /* Signed 8-bit type */
 #define TIFF_INT8_T signed char
 
diff --git a/third_party/tiff_v403/tiffio.h b/third_party/libtiff/tiffio.h
similarity index 98%
rename from third_party/tiff_v403/tiffio.h
rename to third_party/libtiff/tiffio.h
index 4c749ed..038b670 100644
--- a/third_party/tiff_v403/tiffio.h
+++ b/third_party/libtiff/tiffio.h
@@ -298,8 +298,6 @@
 extern void _TIFFmemcpy(void* d, const void* s, tmsize_t c);
 extern int _TIFFmemcmp(const void* p1, const void* p2, tmsize_t c);
 extern void _TIFFfree(void* p);
-/* Do cmyk to rgb convert, add by Sunliang.Liu 20090723. */
-extern	int TIFFCmyk2Rgb(thandle_t context, uint8 c, uint8 m, uint8 y, uint8 k, uint8* r, uint8* g, uint8* b);
 
 /*
 ** Stuff, related to tag handling and creating custom tags.
diff --git a/third_party/tiff_v403/tiffiop.h b/third_party/libtiff/tiffiop.h
similarity index 86%
rename from third_party/tiff_v403/tiffiop.h
rename to third_party/libtiff/tiffiop.h
index c5ddc3c..c647b8d 100644
--- a/third_party/tiff_v403/tiffiop.h
+++ b/third_party/libtiff/tiffiop.h
@@ -1,4 +1,4 @@
-/* $Id: tiffiop.h,v 1.84 2012-05-30 01:50:17 fwarmerdam Exp $ */
+/* $Id: tiffiop.h,v 1.87 2015-08-23 17:49:01 bfriesen Exp $ */
 
 /*
  * Copyright (c) 1988-1997 Sam Leffler
@@ -57,6 +57,12 @@
 		   int (*)(const void *, const void *));
 #endif
 
+#if !defined(HAVE_SNPRINTF) && !defined(HAVE__SNPRINTF)
+#undef snprintf
+#define snprintf _TIFF_snprintf_f
+extern int snprintf(char* str, size_t size, const char* format, ...);
+#endif
+
 #include "tiffio.h"
 
 #include "tif_dir.h"
@@ -258,6 +264,53 @@
 
 #define TIFFArrayCount(a) (sizeof (a) / sizeof ((a)[0]))
 
+/*
+  Support for large files.
+
+  Windows read/write APIs support only 'unsigned int' rather than 'size_t'.
+  Windows off_t is only 32-bit, even in 64-bit builds.
+*/
+#if defined(HAVE_FSEEKO)
+/*
+  Use fseeko() and ftello() if they are available since they use
+  'off_t' rather than 'long'.  It is wrong to use fseeko() and
+  ftello() only on systems with special LFS support since some systems
+  (e.g. FreeBSD) support a 64-bit off_t by default.
+
+  For MinGW, __MSVCRT_VERSION__ must be at least 0x800 to expose these
+  interfaces. The MinGW compiler must support the requested version.  MinGW
+  does not distribute the CRT (it is supplied by Microsoft) so the correct CRT
+  must be available on the target computer in order for the program to run.
+*/
+#if defined(HAVE_FSEEKO)
+#  define fseek(stream,offset,whence)  fseeko(stream,offset,whence)
+#  define ftell(stream,offset,whence)  ftello(stream,offset,whence)
+#endif
+#endif
+#if defined(__WIN32__) && \
+        !(defined(_MSC_VER) && _MSC_VER < 1400) && \
+        !(defined(__MSVCRT_VERSION__) && __MSVCRT_VERSION__ < 0x800)
+typedef unsigned int TIFFIOSize_t;
+#define _TIFF_lseek_f(fildes,offset,whence)  _lseeki64(fildes,/* __int64 */ offset,whence)
+/* #define _TIFF_tell_f(fildes) /\* __int64 *\/ _telli64(fildes) */
+#define _TIFF_fseek_f(stream,offset,whence) _fseeki64(stream,/* __int64 */ offset,whence)
+#define _TIFF_fstat_f(fildes,stat_buff) _fstati64(fildes,/* struct _stati64 */ stat_buff)
+/* #define _TIFF_ftell_f(stream) /\* __int64 *\/ _ftelli64(stream) */
+/* #define _TIFF_stat_f(path,stat_buff) _stati64(path,/\* struct _stati64 *\/ stat_buff) */
+#define _TIFF_stat_s struct _stati64
+#define _TIFF_off_t __int64
+#else
+typedef size_t TIFFIOSize_t;
+#define _TIFF_lseek_f(fildes,offset,whence) lseek(fildes,offset,whence)
+/* #define _TIFF_tell_f(fildes) (_TIFF_lseek_f(fildes,0,SEEK_CUR)) */
+#define _TIFF_fseek_f(stream,offset,whence) fseek(stream,offset,whence)
+#define _TIFF_fstat_f(fildes,stat_buff) fstat(fildes,stat_buff)
+/* #define _TIFF_ftell_f(stream) ftell(stream) */
+/* #define _TIFF_stat_f(path,stat_buff) stat(path,stat_buff) */
+#define _TIFF_stat_s struct stat
+#define _TIFF_off_t off_t
+#endif
+
 #if defined(__cplusplus)
 extern "C" {
 #endif
diff --git a/third_party/tiff_v403/uvcode.h b/third_party/libtiff/uvcode.h
similarity index 100%
rename from third_party/tiff_v403/uvcode.h
rename to third_party/libtiff/uvcode.h
diff --git a/third_party/third_party.gyp b/third_party/third_party.gyp
index 89a4632..b57009c 100644
--- a/third_party/third_party.gyp
+++ b/third_party/third_party.gyp
@@ -329,42 +329,42 @@
           'target_name': 'fx_tiff',
           'type': 'static_library',
           'sources': [
-            'tiff_v403/tiffiop.h',
-            'tiff_v403/tif_aux.c',
-            'tiff_v403/tif_close.c',
-            'tiff_v403/tif_codec.c',
-            'tiff_v403/tif_color.c',
-            'tiff_v403/tif_compress.c',
-            'tiff_v403/tif_dir.c',
-            'tiff_v403/tif_dirinfo.c',
-            'tiff_v403/tif_dirread.c',
-            'tiff_v403/tif_dirwrite.c',
-            'tiff_v403/tif_dumpmode.c',
-            'tiff_v403/tif_error.c',
-            'tiff_v403/tif_extension.c',
-            'tiff_v403/tif_fax3.c',
-            'tiff_v403/tif_fax3sm.c',
-            'tiff_v403/tif_flush.c',
-            'tiff_v403/tif_getimage.c',
-            'tiff_v403/tif_jpeg.c',
-            'tiff_v403/tif_luv.c',
-            'tiff_v403/tif_lzw.c',
-            'tiff_v403/tif_next.c',
-            'tiff_v403/tif_ojpeg.c',
-            'tiff_v403/tif_open.c',
-            'tiff_v403/tif_packbits.c',
-            'tiff_v403/tif_pixarlog.c',
-            'tiff_v403/tif_predict.c',
-            'tiff_v403/tif_print.c',
-            'tiff_v403/tif_read.c',
-            'tiff_v403/tif_strip.c',
-            'tiff_v403/tif_swab.c',
-            'tiff_v403/tif_thunder.c',
-            'tiff_v403/tif_tile.c',
-            'tiff_v403/tif_version.c',
-            'tiff_v403/tif_warning.c',
-            'tiff_v403/tif_write.c',
-            'tiff_v403/tif_zip.c',
+            'libtiff/tiffiop.h',
+            'libtiff/tif_aux.c',
+            'libtiff/tif_close.c',
+            'libtiff/tif_codec.c',
+            'libtiff/tif_color.c',
+            'libtiff/tif_compress.c',
+            'libtiff/tif_dir.c',
+            'libtiff/tif_dirinfo.c',
+            'libtiff/tif_dirread.c',
+            'libtiff/tif_dirwrite.c',
+            'libtiff/tif_dumpmode.c',
+            'libtiff/tif_error.c',
+            'libtiff/tif_extension.c',
+            'libtiff/tif_fax3.c',
+            'libtiff/tif_fax3sm.c',
+            'libtiff/tif_flush.c',
+            'libtiff/tif_getimage.c',
+            'libtiff/tif_jpeg.c',
+            'libtiff/tif_luv.c',
+            'libtiff/tif_lzw.c',
+            'libtiff/tif_next.c',
+            'libtiff/tif_ojpeg.c',
+            'libtiff/tif_open.c',
+            'libtiff/tif_packbits.c',
+            'libtiff/tif_pixarlog.c',
+            'libtiff/tif_predict.c',
+            'libtiff/tif_print.c',
+            'libtiff/tif_read.c',
+            'libtiff/tif_strip.c',
+            'libtiff/tif_swab.c',
+            'libtiff/tif_thunder.c',
+            'libtiff/tif_tile.c',
+            'libtiff/tif_version.c',
+            'libtiff/tif_warning.c',
+            'libtiff/tif_write.c',
+            'libtiff/tif_zip.c',
           ],
         },
       ],
diff --git a/third_party/tiff_v403/tiffvers.h b/third_party/tiff_v403/tiffvers.h
deleted file mode 100644
index 40edc81..0000000
--- a/third_party/tiff_v403/tiffvers.h
+++ /dev/null
@@ -1,9 +0,0 @@
-#define TIFFLIB_VERSION_STR "LIBTIFF, Version 4.0.3\nCopyright (c) 1988-1996 Sam Leffler\nCopyright (c) 1991-1996 Silicon Graphics, Inc."
-/*
- * This define can be used in code that requires
- * compilation-related definitions specific to a
- * version or versions of the library.  Runtime
- * version checking should be done based on the
- * string returned by TIFFGetVersion.
- */
-#define TIFFLIB_VERSION 20120922