Fix loading of targa image files (#1478).
[dcpomatic.git] / src / lib / ffmpeg_image_proxy.cc
index e38b80be1942085d9160891a29edff428fd3425a..87925dabc9360f660115f00d7d668dac0cd3b086 100644 (file)
@@ -84,6 +84,9 @@ int
 FFmpegImageProxy::avio_read (uint8_t* buffer, int const amount)
 {
        int const to_do = min(int64_t(amount), _data.size() - _pos);
+       if (to_do == 0) {
+               return AVERROR_EOF;
+       }
        memcpy (buffer, _data.data().get() + _pos, to_do);
        _pos += to_do;
        return to_do;
@@ -132,7 +135,20 @@ FFmpegImageProxy::image (optional<dcp::Size>) const
 
        int e = avformat_open_input (&format_context, 0, 0, &options);
        if (e < 0) {
-               throw OpenFileError (_path->string(), e, true);
+               if (e == AVERROR_INVALIDDATA) {
+                       /* Hack to fix loading of .tga files through AVIOContexts (rather then
+                          directly from the file).  This code just does enough to allow the
+                          probe code to take a hint from "foo.tga" and so try targa format.
+                       */
+                       AVInputFormat* f = av_find_input_format ("image2");
+                       format_context = avformat_alloc_context ();
+                       format_context->pb = avio_context;
+                       format_context->iformat = f;
+                       e = avformat_open_input (&format_context, "foo.tga", f, &options);
+               }
+               if (e < 0) {
+                       throw OpenFileError (_path->string(), e, true);
+               }
        }
 
        if (avformat_find_stream_info(format_context, 0) < 0) {
@@ -167,7 +183,9 @@ FFmpegImageProxy::image (optional<dcp::Size>) const
 
        _image.reset (new Image (frame));
 
+       av_packet_unref (&packet);
        av_frame_free (&frame);
+       avcodec_close (codec_context);
        avformat_close_input (&format_context);
        av_free (avio_context->buffer);
        av_free (avio_context);