classdef FFMPEGVideoDecoderMetricItem < MetricItem
    
    methods (Abstract)
        m=calc_color_imagemetric(fname1,fname2)
    end
    
    
    methods
        function obj=FFMPEGVideoDecoderMetricItem(name)
            obj=obj@MetricItem(name);
        end
        
        function fl=getfilelist(obj,filemask)
            fl=dir(filemask);
        end
        
        function m=avgimagemetric(obj,filemask1,filemask2)
            fl1=getfilelist(obj,filemask1);
            fl2=getfilelist(obj,filemask2);
            
            if length(fl1)~=length(fl2)
                error('File lists are not equal in length');
            else
                nF=length(fl1);
            end
            
            parfor iF=1:nF,
                iF
                fname1=sprintf('decodedimages/%s',fl1(iF).name);
                fname2=sprintf('decodedimages/%s',fl2(iF).name);
                m(iF)=obj.calc_color_imagemetric(fname1,fname2);
            end
            m=mean(m);
        end
        
        function val=calc(obj,item1,item2)
             [val,isCached]=obj.CheckCache(item1,item2);  
             if ~isCached   
             fprintf('Extracting  images .... \n');
             [fmask1,fmask2]=obj.decompressvideos(item1,item2);
             fprintf('Calculating video metric .... \n');
             val=obj.avgimagemetric(fmask1,fmask2);
             obj.StoreToCache(item1,item2,val); 
             end
        end
        
        
        function [item1png_name_mask,item2png_name_mask]=decompressvideos(obj,item1,item2)
            [fpathstr,fname1,fext] = fileparts(item1.getfilename);
            [fpathstr,fname2,fext] = fileparts(item2.getfilename);
            
            % TODO: check this !
            item1namecheck=sprintf('decodedimages/decoded1_%s_0001.png',fname1);
            item2namecheck=sprintf('decodedimages/decoded2_%s_0001.png',fname2);
            
            item1png_name=sprintf('decodedimages/decoded1_%s_%%4d.png',fname1);
            item2png_name=sprintf('decodedimages/decoded2_%s_%%4d.png',fname2);
            
            item1png_name_mask=sprintf('decodedimages/decoded1_%s_*.png',fname1);
            item2png_name_mask=sprintf('decodedimages/decoded2_%s_*.png',fname2);
            
            if ~exist('decodedimages','dir')
                mkdir('decodedimages');
            end
            
            if ~exist(item1namecheck,'file')
                dos(sprintf('ffmpeg -i %s -an -f image2 -pix_fmt rgb24 %s',item1.getfilename,item1png_name));
            end
            
            if ~exist(item2namecheck,'file')
                dos(sprintf('ffmpeg -i %s -an -f image2 -pix_fmt rgb24 %s',item2.getfilename,item2png_name));
            end
        end
    end
    
end