%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%    
%%
%% Working with Videos in Matlab
%%
%% There are three relevant functions:
%%
%% mmfileinfo    - Information about a multimedia file.
%% VideoReader   - Create a multimedia reader object.
%% VideoWriter   - Create a video writer object.
    
    
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%    
%% Get info about the properties of a video file
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%    

help mmfileinfo

v=mmfileinfo('backgammon.m4v')

v.Duration
v.Filename
v.Path 

v.Video.Width
v.Video.Height
v.Video.Format

v.Audio.Format
v.Audio.NumberOfChannels


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%    
%% Read and display a video file
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%    
vr = VideoReader('backgammon.m4v');
vr.CurrentTime = 0.0;

while hasFrame(vr)
    frame = readFrame(vr);
    imshow(frame)
    pause(1/vr.FrameRate);
end

% Rewind
vr.CurrentTime = 5.0;

while hasFrame(vr)
    frame = readFrame(vr);
    imshow(frame)
    pause(1/vr.FrameRate);
end
 
 

% reading a specific frame
firstFrame = read(vr,1);
lastFrame = read(vr,Inf);

figure; imshow(firstFrame)
figure; imshow(lastFrame)

% reading a range of frames
rangeOfFrames = read(vr,[5 10]);

figure; imshow(rangeOfFrames(:,:,:,1))
figure; imshow(rangeOfFrames(:,:,:,6))


% help VideoReader
%         
%  Methods:
%      read              - Read one or more frames from a video file.
%      readFrame         - Read the next available frame from a video file.
%      hasFrame          - Determine if there is a frame available to read
%                          from a video file. 
%      getFileFormats    - List of known supported video file formats.
%         
% 
%  Properties:
%      Name             - Name of the file to be read.
%      Path             - Path of the file to be read.
%      Duration         - Total length of file in seconds.
%      CurrentTime      - Location from the start of the file of the current
%                         frame to be read in seconds. 
%      Tag              - Generic text for the user to set.
%      UserData         - Generic field for any user-defined data.
% 
%      Height           - Height of the video frame in pixels.
%      Width            - Width of the video frame in pixels.
%      BitsPerPixel     - Bits per pixel of the video data.
%      VideoFormat      - Video format as it is represented in MATLAB.
%      FrameRate        - Frame rate of the video in frames per second.
      
  
  
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%    
%% Create and write to a video file
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%     
help VideoWriter

vw = VideoWriter('small.m4v', 'MPEG-4');
open(vw); % open the file

vr.CurrentTime = 0.0;
while hasFrame(vr)
    frame = readFrame(vr);
    small_frame=impyramid(frame, 'reduce');
    writeVideo(vw, small_frame);
end

close(vw);  % close the file

