MATLAB: How to recover an AVI file that I am writing if MATLAB crashes on the Mac or UNIX

MATLAB

I want to recover an AVI file that I am writting when MATLAB crashes on my Mac or UNIX computer.

Best Answer

On Mac when we add frames to an AVI file, we actually create a temporary file in the /tmp directory with a .tmp extension. The file contains the raw image data saved on every addframe call, and all the data is written to the avi file upon the 'close' call.
If MATLAB does crash, or if your program stops running for other reasons, that .tmp file (usually named something random like p4be293e3_d112_4907_8e9a_c9a3dbfdade6.tmp) will still be in the /tmp directory, so you could feasibly recover the image data if you needed to. However, the data is just raw uncompressed image data and not formatted in an AVI structure.
To find out where the temporary directory is on your platform type:
tempdir
at the MATLAB command prompt.
To find out the exact temporary file that is being generated, you can put a breakpoint on line 94 of avifile/avifile.m to see the exact temporary name that gets created. Avifile makes use of the 'tempname' function which generated an arbitrary temporary file name for you.
You can look through the code starting at line 95 in avifile/close.m for example code of how to read form the temporary file. Here it is also for convenience:
% Open temp data and copy to avi file
TempDataFile = fopen(aviobj.TempDataFile,'r','l');
if TempDataFile == -1
error('MATLAB:aviclose:unableToOpenTempFile',['Unable to open
temporary file' aviobj.TempDataFile '.']);
end
offsets = zeros(1,aviobj.MainHeader.TotalFrames);
ChunkSizes = zeros(1,aviobj.MainHeader.TotalFrames);
for i = 1:aviobj.MainHeader.TotalFrames
chunkid = fread(TempDataFile,4,'char');
ChunkSizes(i) = fread(TempDataFile,1,'uint32');
data = fread(TempDataFile,ChunkSizes(i),'*uint8');
if aviobj.Compression == 0
[offsets(i), pad] = WriteUncompressedData(fid, aviobj, data);
elseif aviobj.Compression == 1
[offsets(i), pad] = WriteCompressedData(fid, aviobj, data);
end
end
This code could easily be adapted to read each frame into memory again.