home *** CD-ROM | disk | FTP | other *** search
/ Freelog 125 / Freelog_MarsAvril2015_No125.iso / Multimedia / AVStoDVD / AVStoDVD_Portable.exe / AVStoDVD_Portable / Wavi / src / wavi.c < prev   
C/C++ Source or Header  |  2011-06-16  |  16KB  |  437 lines

  1. #include <windows.h>
  2. #include <vfw.h>
  3. #include <stdio.h>
  4.  
  5. #define VERSION "1.06m"
  6. /*
  7. 1.06m: add tebasuna51's patch, and fix crash in some case (Chikuzen)
  8. 1.06: option to write extended WAV header with channel mask (thanks to tebasuna51)
  9. 1.05: performance optimization 
  10. 1.04: added support for floating-point samples (thanks to tebasuna51)
  11. 1.03: fixed size field in data chunk header (thanks to tebasuna51)
  12. 1.03: don't expect that AVIStreamRead stops at the end of the stream (thanks to tebasuna51)
  13. */
  14.  
  15. #define WAVE_FORMAT_IEEE_FLOAT 3
  16.  
  17. DWORD WINAPI FileWriterThread(LPVOID param);
  18. VOID CleanupAndExit(UINT exitCode);
  19. BOOL CtrlHandler(DWORD ctrlType);
  20.  
  21. #define BUFFER_SIZE 0x20000
  22. #define DEFAULT_MASK_COUNT 9
  23. static DWORD DEFAULT_MASK[9] = {0, 4, 3, 259, 51, 55, 63, 319, 255};
  24.  
  25. LPSTR         inputFile     = NULL;
  26. LPSTR         outputFile    = NULL;
  27. BOOL          rawOutput     = FALSE;
  28. BOOL          wavexOutput   = FALSE;
  29. DWORD         channelMask   = 0xFFFFFFFF;
  30. PAVIFILE      aviFile       = NULL;
  31. BOOL          lookForStream = TRUE;
  32. LONG          streamID      = 0;
  33. PAVISTREAM    aviStream     = NULL;
  34. AVISTREAMINFO streamInfo;
  35. WAVEFORMATEX  waveFormat;
  36. LONG          formatSize    = sizeof(WAVEFORMATEX);
  37. DWORD         sampleSize;
  38. BOOL          hasSomeAudio  = FALSE;
  39. DWORDLONG     fileSize;
  40. DWORD         samplesInBuffer;
  41. BYTE          wavHeader[68];
  42. DWORD         headerPos = 0;
  43. BOOL          toStdOut;
  44. HANDLE        outputHandle;
  45. HANDLE        readEvent = NULL;
  46. HANDLE        writeEvent = NULL;
  47. HANDLE        writerThread = NULL;
  48. DWORD         writerThreadID;
  49. int           readBuffer = 0;
  50. int           writeBuffer = 0;
  51. LPBYTE        buffer[2][BUFFER_SIZE];
  52. DWORD         bytesToWrite[2];
  53. DWORD         bytesWritten;
  54. DWORD         samplesRead;
  55. DWORD         nextSample = 0;
  56. BOOL          userBreak = FALSE;
  57.  
  58. int main(int argc, char * argv[])
  59. {
  60.     AVIFileInit();
  61.     SetConsoleCtrlHandler((PHANDLER_ROUTINE) CtrlHandler, TRUE);
  62.     
  63.     if (argc < 2) {
  64.         fprintf(stderr, 
  65.             "WAVI v" VERSION " - (c) 2007 Tamas Kurucsai, with lots of help from tebasuna51\n"
  66.             "Licensed under the terms of the GNU General Public License.\n"
  67.             "\n"
  68.             "This utility extracts the first uncompressed PCM audio track\n"
  69.             "from an AVI file and saves it to a WAV file. This is not quite\n"
  70.             "useful for most AVI files since they usually contain some kind\n"
  71.             "of compressed audio, but it can come handy when it's needed to\n"
  72.             "save an audio track from AviSynth.\n"
  73.             "\n"
  74.             "Usage: WAVI <avi-file> [ <wav-file> [ /R | /X | /M <mask> ] ]\n"
  75.             "\n"
  76.             "If <avi-file> is a valid AVI file which contains PCM audio,\n"
  77.             "the audio track will be written to <wav-file> as a WAV file.\n"
  78.             "If '-' is passed as <wav-file>, the WAV file will be written\n"
  79.             "to the standard output.\n"
  80.             "If <wav-file> is not given, only information will be printed\n"
  81.             "about the audio track.\n"
  82.             "\n"
  83.             "On success, the exit code will be 0 and the first line printed\n"
  84.             "to the standard error will look like the following:\n"
  85.             "\n"
  86.             "Found PCM audio: <c> channels, <r> Hz, <b> bits, <l> seconds.\n"
  87.             "\n"
  88.             "where <c> is the number of audio channels, <r> is the sampling\n"
  89.             "rate, <b> is the number of bits per sample and <l> is the length\n"
  90.             "of the track in seconds.\n"
  91.             "\n"
  92.             "If the audio track contains floating-point samples, the next line\n"
  93.             "printed to the standard error will be:\n"
  94.             "Audio track contains floating-point samples.\n"
  95.             "\n"
  96.             "If an error occurs, the exit code will be 1 and some useful error\n"
  97.             "message will be printed to the standard error.\n"
  98.             "\n"
  99.             "WAV files larger than 4 GB may be created. However, such WAV files\n"
  100.             "are non-standard and may not be handled correctly by some players\n"
  101.             "and encoders. A warning will be printed to the standard error when\n"
  102.             "such a WAV file is created.\n"
  103.             "\n"
  104.             "WAVI accepts the following options:\n"
  105.             "\n"
  106.             "/R - Write a raw file of samples without the WAV header.\n"
  107.             "\n"
  108.             "/X - Write an extended WAV header containing the default\n"
  109.             "     channel mask for multi-channel audio.\n"
  110.             "\n"
  111.             "/M <mask> - Write an extended WAV header containing the\n"
  112.             "     specified channel mask for multi-channel audio.\n"
  113.             "\n"
  114.             "The default channel masks are:\n"
  115.             "\n"
  116.             "Mask  Chan. MS channels                Description\n"
  117.             "----  ----- -------------------------  ----------------\n"
  118.             "   4   1    FC                         Mono\n"
  119.             "   3   2    FL FR                      Stereo\n"
  120.             " 259   3    FL FR BC                   First Surround\n"
  121.             "  51   4    FL FR BL BR                Quadro\n"
  122.             "  55   5    FL FR FC BL BR             like Dpl II (without LFE)\n"
  123.             "  63   6    FL FR FC LF BL BR          Standard Surround\n"
  124.             " 319   7    FL FR FC LF BL BR BC       With back center\n"
  125.             " 255   8    FL FR FC LF BL BR FLC FRC  With front center left/right\n"
  126.             "\n"
  127.             "Some other common channel masks:\n"
  128.             "\n"
  129.             "Mask  Chan. MS channels                Description\n"
  130.             "----  ----- -------------------------  ----------------\n"
  131.             "   7   3    FL FR FC\n"
  132.             " 263   4    FL FR FC BC                like Dpl I\n"
  133.             " 271   5    FL FR FC BC LF\n"
  134.             "  59   5    FL FR BL BR LF\n"
  135.             );
  136.         CleanupAndExit(1);
  137.         } else {
  138.             int actarg = 0;
  139.             BOOL maskComing = FALSE;
  140.             while (argv[++actarg]) {
  141.                 if ((argv[actarg][0] == '-' || argv[actarg][0] == '/') && argv[actarg][1]) {
  142.                     if (maskComing) {
  143.                     fprintf(stderr, "Error: Channel mask expected after %s.\n", argv[actarg - 1]);
  144.                     CleanupAndExit(1);
  145.                 }
  146.                     switch (argv[actarg][1]) {
  147.                     case 'r':
  148.                     case 'R':
  149.                         rawOutput = TRUE;
  150.                         break;
  151.                     case 'm':
  152.                     case 'M':
  153.                         maskComing = TRUE;
  154.                     case 'x':
  155.                     case 'X':
  156.                         wavexOutput = TRUE;
  157.                         break;
  158.                     default:
  159.                         fprintf(stderr, "Error: Invalid option %s.\n", argv[actarg]);
  160.                     CleanupAndExit(1);
  161.                     break;
  162.                 }
  163.                 } else {
  164.                     if (maskComing) {
  165.                         channelMask = atoi(argv[actarg]);
  166.                         if (! channelMask) {
  167.                         fprintf(stderr, "Error: Channel mask expected after %s.\n", argv[actarg - 1]);
  168.                         CleanupAndExit(1);
  169.                     }
  170.                         maskComing = FALSE;
  171.                     } else if (! inputFile) {
  172.                         inputFile = argv[actarg];
  173.                     } else if (! outputFile) {
  174.                         outputFile = argv[actarg];
  175.                     } else {
  176.                     fprintf(stderr, "Error: Too many parameters.\n");
  177.                     CleanupAndExit(1);
  178.                     }
  179.                 }
  180.             }
  181.         if (maskComing) {
  182.             fprintf(stderr, "Error: Channel mask expected after %s.\n", argv[actarg - 1]);
  183.             CleanupAndExit(1);
  184.         } else if (! inputFile) {
  185.             fprintf(stderr, "Error: Missing input file.\n");
  186.             CleanupAndExit(1);
  187.         }
  188.     }
  189.     if (userBreak) CleanupAndExit(1);
  190.     
  191.     if (AVIFileOpen(& aviFile, inputFile, OF_READ | OF_SHARE_DENY_WRITE, NULL)) {
  192.         fprintf(stderr, "Error: Could not open AVI file \"%s\".\n", inputFile);
  193.         CleanupAndExit(1);
  194.     }
  195.     if (userBreak) CleanupAndExit(1);
  196.     while (lookForStream) {
  197.         if (! AVIFileGetStream(aviFile, & aviStream, 0, streamID)) {
  198.             if (! AVIStreamInfo(aviStream, & streamInfo, sizeof(AVISTREAMINFO))) {
  199.                 if (streamInfo.fccType == streamtypeAUDIO) {
  200.                     hasSomeAudio = TRUE;
  201.                     if (! AVIStreamReadFormat(aviStream, 0, & waveFormat, & formatSize)) {
  202.                         if (waveFormat.wFormatTag == WAVE_FORMAT_PCM || waveFormat.wFormatTag == WAVE_FORMAT_IEEE_FLOAT) {
  203.                             if (! AVIStreamSampleSize(aviStream, 0, & sampleSize)) {
  204.                                 lookForStream = FALSE;
  205.                             }
  206.                         }
  207.                     }
  208.                 }
  209.             }
  210.             if (lookForStream) {
  211.                 AVIStreamRelease(aviStream);
  212.                 aviStream = NULL;
  213.                 streamID++;
  214.             }
  215.         } else {
  216.             lookForStream = FALSE;
  217.         }
  218.         if (userBreak) CleanupAndExit(1);
  219.     }
  220.     if (! aviStream) {
  221.         fprintf(stderr, "Error: Could not find PCM audio track in \"%s\".\n", inputFile);
  222.         if (hasSomeAudio) {
  223.             fprintf(stderr, "(However, the file contains an audio track of another format.)\n");
  224.         }
  225.         CleanupAndExit(1);
  226.     } 
  227.         fprintf(stderr, "Found PCM audio: %d channels, %d Hz, %d bits, %f seconds.\n", 
  228.         waveFormat.nChannels, waveFormat.nSamplesPerSec, waveFormat.wBitsPerSample,
  229.         1.0 * streamInfo.dwLength * streamInfo.dwScale / streamInfo.dwRate);
  230.     if (waveFormat.wFormatTag == WAVE_FORMAT_IEEE_FLOAT) {
  231.         fprintf(stderr, "Audio track contains floating-point samples.\n");
  232.     }
  233.         
  234.     if (outputFile) {
  235.         fileSize = UInt32x32To64(sampleSize, streamInfo.dwLength);
  236.         if (fileSize > 0xFFFFFFFF - (wavexOutput ? 60 : 36)) {
  237.             fprintf(stderr, "Warning: WAV file will be larger than 4 GB.\n");
  238.             fileSize = sampleSize * ((0xFFFFFFFF - (wavexOutput ? 60 : 36)) / sampleSize);
  239.         }
  240.         samplesInBuffer = BUFFER_SIZE / sampleSize;
  241.         if (! samplesInBuffer) {
  242.             fprintf(stderr, "Error: Too large samples; audio track is definitely invalid.\n");
  243.             CleanupAndExit(1);
  244.         }
  245.         if (wavexOutput && (channelMask == 0xFFFFFFFF)) {
  246.             if (waveFormat.nChannels < DEFAULT_MASK_COUNT) {
  247.                 channelMask = DEFAULT_MASK[waveFormat.nChannels];
  248.             } else {
  249.                 channelMask = (1 << waveFormat.nChannels) - 1;
  250.             }
  251.         }
  252.  
  253.         if (! rawOutput) {
  254.             wavHeader[headerPos++] = 'R';
  255.             wavHeader[headerPos++] = 'I';
  256.             wavHeader[headerPos++] = 'F';
  257.             wavHeader[headerPos++] = 'F';
  258.             *(LPDWORD)(wavHeader + headerPos) = (DWORD) fileSize + (wavexOutput ? 60 : 36);
  259.             headerPos += 4;
  260.             wavHeader[headerPos++] = 'W';
  261.             wavHeader[headerPos++] = 'A';
  262.             wavHeader[headerPos++] = 'V';
  263.             wavHeader[headerPos++] = 'E';
  264.             wavHeader[headerPos++] = 'f';
  265.             wavHeader[headerPos++] = 'm';
  266.             wavHeader[headerPos++] = 't';
  267.             wavHeader[headerPos++] = ' ';
  268.             *(LPDWORD)(wavHeader + headerPos) = (wavexOutput ? 40 : 16);
  269.             headerPos += 4;
  270.             *(LPWORD)(wavHeader + headerPos)  = (wavexOutput ? 0xFFFE : waveFormat.wFormatTag);
  271.             headerPos += 2;
  272.             *(LPWORD)(wavHeader + headerPos)  = waveFormat.nChannels;
  273.             headerPos += 2;
  274.             *(LPDWORD)(wavHeader + headerPos) = waveFormat.nSamplesPerSec;
  275.             headerPos += 4;
  276.             *(LPDWORD)(wavHeader + headerPos) = waveFormat.nAvgBytesPerSec;
  277.             headerPos += 4;
  278.             *(LPWORD)(wavHeader + headerPos)  = waveFormat.nBlockAlign;
  279.             headerPos += 2;
  280.             *(LPWORD)(wavHeader + headerPos)  = waveFormat.wBitsPerSample;
  281.             headerPos += 2;
  282.                         if (wavexOutput) {
  283.                              *(LPWORD)(wavHeader + headerPos)  = 22;
  284.                              headerPos += 2;
  285.                              *(LPWORD)(wavHeader + headerPos)  = waveFormat.wBitsPerSample;
  286.                              headerPos += 2;
  287.                              *(LPDWORD)(wavHeader + headerPos) = channelMask;
  288.                              headerPos += 4;
  289.                              *(LPWORD)(wavHeader + headerPos)  = waveFormat.wFormatTag;
  290.                              headerPos += 2;
  291.                              *(LPWORD)(wavHeader + headerPos)  = 0x0000;
  292.                              headerPos += 2;
  293.                              *(LPDWORD)(wavHeader + headerPos) = 0x00100000;
  294.                              headerPos += 4;
  295.                              //see http://sourceforge.net/tracker/?func=detail&aid=2957741&group_id=196137&atid=956250
  296.                              // *(LPDWORD)(wavHeader + headerPos) = 0x00AA8000;
  297.                              *(LPDWORD)(wavHeader + headerPos) = 0xAA000080;
  298.                              headerPos += 4;
  299.                              // *(LPDWORD)(wavHeader + headerPos) = 0x9B713800;
  300.                              *(LPDWORD)(wavHeader + headerPos) = 0x719B3800;
  301.                              headerPos += 4;
  302.                         }
  303.             wavHeader[headerPos++] = 'd';
  304.             wavHeader[headerPos++] = 'a';
  305.             wavHeader[headerPos++] = 't';
  306.             wavHeader[headerPos++] = 'a';
  307.             *(LPDWORD)(wavHeader + headerPos) = (DWORD) fileSize;
  308.             headerPos += 4;
  309.         }
  310.  
  311.         toStdOut = ! strcmp(outputFile, "-");
  312.         if (toStdOut) {
  313.             outputHandle = GetStdHandle(STD_OUTPUT_HANDLE);
  314.             fprintf(stderr, "Writing WAV file...\n");
  315.         } else {
  316.             outputHandle = CreateFile(outputFile, GENERIC_WRITE, FILE_SHARE_READ, 
  317.                 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
  318.             if (outputHandle == INVALID_HANDLE_VALUE) {
  319.                 fprintf(stderr, "Error: Could not create file \"%s\".\n", outputFile);
  320.                 CleanupAndExit(1);
  321.             }
  322.             fprintf(stderr, "Writing WAV file \"%s\"...\n", outputFile);
  323.         }
  324.             
  325.         if (headerPos) {
  326.             if (! WriteFile(outputHandle, wavHeader, headerPos, & bytesWritten, NULL) || (bytesWritten != headerPos)) {
  327.                 if (toStdOut) {
  328.                     fprintf(stderr, "Error: Could not write to the standard output.\n");
  329.                 } else {
  330.                     fprintf(stderr, "Error: Could not write file \"%s\".\n", outputFile);
  331.                     CloseHandle(outputHandle);
  332.                 }
  333.                 CleanupAndExit(1);
  334.             }
  335.         }
  336.         
  337.         readEvent = CreateEvent(NULL, FALSE, TRUE, NULL);
  338.         writeEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
  339.         writerThread = CreateThread(NULL, 0, FileWriterThread, NULL, CREATE_SUSPENDED, & writerThreadID);
  340.         if (! readEvent || ! writeEvent || ! writerThread) {
  341.             fprintf(stderr, "Error: An internal error occured.\n");
  342.             if (! toStdOut) CloseHandle(outputHandle);
  343.             CleanupAndExit(1);
  344.         }
  345.         ResumeThread(writerThread);
  346.         
  347.         while (nextSample < streamInfo.dwLength) {
  348.             if (userBreak) CleanupAndExit(1);
  349.             WaitForSingleObject(readEvent, INFINITE);
  350.             if (userBreak) CleanupAndExit(1);
  351.             if (streamInfo.dwLength - nextSample < samplesInBuffer) {
  352.                 samplesInBuffer = streamInfo.dwLength - nextSample;
  353.             }
  354.             bytesToWrite[readBuffer] = 0;
  355.             if (AVIStreamRead(aviStream, nextSample, samplesInBuffer, & buffer[readBuffer], BUFFER_SIZE, 
  356.                               & bytesToWrite[readBuffer], & samplesRead) || (! bytesToWrite[readBuffer])) {
  357.                 fprintf(stderr, "Error: Could not read audio data from \"%s\".\n", inputFile);
  358.                 if (! toStdOut) CloseHandle(outputHandle);
  359.                 CleanupAndExit(1);
  360.             }
  361.             SetEvent(writeEvent);
  362.             nextSample += samplesRead;
  363.             readBuffer = 1 - readBuffer;
  364.         }
  365.         if (userBreak) CleanupAndExit(1);
  366.         WaitForSingleObject(readEvent, INFINITE);
  367.         if (userBreak) CleanupAndExit(1);
  368.         bytesToWrite[readBuffer] = 0;
  369.         SetEvent(writeEvent);
  370.         WaitForSingleObject(writerThread, INFINITE);
  371.         
  372.         if (! toStdOut && ! CloseHandle(outputHandle)) {
  373.             fprintf(stderr, "Error: Could not write file \"%s\".\n", outputFile);
  374.             CleanupAndExit(1);
  375.         }
  376.         
  377.         fprintf(stderr, "WAV file written successfully.\n");
  378.     }
  379.     
  380.     CleanupAndExit(0);
  381.     return 0;
  382. }
  383.  
  384. DWORD WINAPI FileWriterThread(LPVOID Param)
  385. {
  386.     while (42) {
  387.         WaitForSingleObject(writeEvent, INFINITE);
  388.         if (bytesToWrite[writeBuffer]) {
  389.             if (! WriteFile(outputHandle, buffer[writeBuffer], bytesToWrite[writeBuffer], & bytesWritten, NULL) 
  390.                 || (bytesWritten != bytesToWrite[writeBuffer])) {
  391.                 if (toStdOut) {
  392.                     fprintf(stderr, "Error: Could not write to the standard output.\n");
  393.                 } else {
  394.                     fprintf(stderr, "Error: Could not write file \"%s\".\n", outputFile);
  395.                     CloseHandle(outputHandle);
  396.                 }
  397.                 CleanupAndExit(1);
  398.             }
  399.             bytesToWrite[writeBuffer] = 0;
  400.             SetEvent(readEvent);
  401.             writeBuffer = 1 - writeBuffer;
  402.         } else {
  403.             return 0;
  404.         }
  405.     } 
  406. }
  407.  
  408. VOID CleanupAndExit(UINT exitCode)
  409. {
  410.     if (writerThread) CloseHandle(writerThread);
  411.     if (writeEvent)   CloseHandle(writeEvent);
  412.     if (readEvent)    CloseHandle(readEvent);
  413. //    if (buffer)       LocalFree((HLOCAL) buffer); This is not only meaningless but also often causes the crash.
  414.     if (aviStream)    AVIStreamRelease(aviStream);
  415.     if (aviFile)      AVIFileRelease(aviFile);
  416.     AVIFileExit();
  417.     ExitProcess(exitCode);
  418. }
  419.  
  420. BOOL CtrlHandler(DWORD ctrlType)
  421. {
  422.     switch (ctrlType) 
  423.     {
  424.     case CTRL_C_EVENT:
  425.     case CTRL_BREAK_EVENT:
  426.         if (! userBreak) {
  427.             fprintf(stderr, "User break.\n");
  428.             userBreak = TRUE;
  429.         } else {
  430.             fprintf(stderr, "Please wait a bit until everything is cleaned up.\n");
  431.         }
  432.         return TRUE;
  433.     default:
  434.         return TRUE;
  435.     }
  436. }
  437.