/*
 * Copyright 2002-2019 Drew Noakes and contributors
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 *
 * More information about this project is available at:
 *
 *    https://drewnoakes.com/code/exif/
 *    https://github.com/drewnoakes/metadata-extractor
 */
package com.drew.imaging.riff;

import com.drew.lang.SequentialReader;
import com.drew.lang.annotations.NotNull;

import java.io.IOException;

/**
 * Processes RIFF-formatted data, calling into client code via that {@link RiffHandler} interface.
 * <p></p>
 * For information on this file format, see:
 * <ul>
 *     <li>http://en.wikipedia.org/wiki/Resource_Interchange_File_Format</li>
 *     <li>https://developers.google.com/speed/webp/docs/riff_container</li>
 *     <li>https://www.daubnet.com/en/file-format-riff</li>
 * </ul>
 * @author Drew Noakes https://drewnoakes.com
 * @author Payton Garland
 */
public class RiffReader
{
    /**
     * Processes a RIFF data sequence.
     *
     * @param reader the {@link SequentialReader} from which the data should be read
     * @param handler the {@link RiffHandler} that will coordinate processing and accept read values
     * @throws RiffProcessingException if an error occurred during the processing of RIFF data that could not be
     *                                 ignored or recovered from
     * @throws IOException an error occurred while accessing the required data
     */
    public void processRiff(@NotNull final SequentialReader reader,
                            @NotNull final RiffHandler handler) throws RiffProcessingException, IOException
    {
        // RIFF files are always little-endian
        reader.setMotorolaByteOrder(false);

        // PROCESS FILE HEADER

        final String fileFourCC = reader.getString(4);

        if (!fileFourCC.equals("RIFF"))
            throw new RiffProcessingException("Invalid RIFF header: " + fileFourCC);

        // The total size of the chunks that follow plus 4 bytes for the FourCC
        final int fileSize = reader.getInt32();
        int sizeLeft = fileSize;

        final String identifier = reader.getString(4);
        sizeLeft -= 4;

        if (!handler.shouldAcceptRiffIdentifier(identifier))
            return;

        // PROCESS CHUNKS
        processChunks(reader, sizeLeft, handler);
    }

    public void processChunks(SequentialReader reader, int sectionSize, RiffHandler handler) throws IOException
    {
        while (reader.getPosition() < sectionSize) {
            String fourCC = new String(reader.getBytes(4));
            int size = reader.getInt32();
            if (fourCC.equals("LIST") || fourCC.equals("RIFF")) {
                String listName = new String(reader.getBytes(4));
                if (handler.shouldAcceptList(listName)) {
                    processChunks(reader, size - 4, handler);
                } else {
                    reader.skip(size - 4);
                }
            } else if (fourCC.equals("IDIT")) {
                // Avi DateTimeOriginal
                handler.processChunk(fourCC, reader.getBytes(size-2));
                reader.skip(2); // ?0A 00?
            } else {
                if (handler.shouldAcceptChunk(fourCC)) {
                    // TODO is it feasible to avoid copying the chunk here, and to pass the sequential reader to the handler?
                    handler.processChunk(fourCC, reader.getBytes(size));
                } else {
                    reader.skip(size);
                }
                // Bytes read must be even - skip one if not
                if ((size & 1) == 1) {
                    reader.skip(1);
                }
            }
        }
    }
}

@@ -2939,32 +2939,50 @@
 Exception%0A    %7B%0A
+        try %7B%0A    
         while (r
@@ -3026,24 +3026,28 @@
             
+    
 String fourC
@@ -3086,32 +3086,36 @@
 ));%0A            
+    
 int size = reade
@@ -3136,24 +3136,28 @@
             
+ 
+   
 if (fourCC.e
@@ -3210,24 +3210,28 @@
             
+    
 String listN
@@ -3260,32 +3260,172 @@
 r.getBytes(4));%0A
+                    if (size %3C 4) %7B%0A                        handler.addError(%22Chunk size too small.%22);%0A                    %7D else %7B%0A        
                 
@@ -3462,24 +3462,32 @@
 istName)) %7B%0A
+        
             
@@ -3532,24 +3532,32 @@
 , handler);%0A
+        
             
@@ -3581,32 +3581,40 @@
                 
+        
 reader.skip(size
@@ -3628,34 +3628,68 @@
                 
-%7D%0A
+        %7D%0A                    %7D%0A    
             %7D el
@@ -3736,16 +3736,20 @@
         
+    
 // Avi D
@@ -3764,16 +3764,156 @@
 riginal%0A
+                    if (size %3C 2) %7B%0A                        handler.addError(%22Chunk size too small.%22);%0A                    %7D else %7B%0A        
         
@@ -3969,17 +3969,19 @@
 tes(size
--
+ - 
 2));%0A   
@@ -3985,32 +3985,40 @@
                 
+ 
+       
 reader.skip(2); 
@@ -4028,16 +4028,42 @@
 ?0A 00?%0A
+                    %7D%0A    
         
@@ -4083,32 +4083,36 @@
                 
+ 
+   
 if (handler.shou
@@ -4132,24 +4132,28 @@
 (fourCC)) %7B%0A
+    
             
@@ -4278,32 +4278,36 @@
                 
+    
 handler.processC
@@ -4351,32 +4351,36 @@
                 
+    
 %7D else %7B%0A       
@@ -4384,32 +4384,36 @@
                 
+   
+ 
 reader.skip(size
@@ -4423,34 +4423,42 @@
                 
-%7D%0A
+    %7D%0A    
                 
@@ -4514,24 +4514,28 @@
             
+    
 if ((size & 
@@ -4541,24 +4541,28 @@
  1) == 1) %7B%0A
+    
             
@@ -4605,23 +4605,125 @@
     
-%7D%0A            %7D
+    %7D%0A                %7D%0A            %7D%0A        %7D catch (IOException e) %7B%0A            handler.addError(e.getMessage());
 %0A   

Handle IOException in RIFF files