toMKV.sh 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #!/bin/bash
  2. # Command line
  3. inFile="${1}"
  4. outFile="${2}"
  5. movLength="${3}"
  6. if [ -z "${inFile}" ] || [ ! -e "${inFile}" ]; then
  7. echo "Usage: `basename "${0}"` input_file [output_file] [mov_length]" 1>&2
  8. exit 1
  9. fi
  10. # Grab some codec info
  11. INFO="`~/bin/video/movInfo.pl "${inFile}"`"
  12. ACODECS="`echo "${INFO}" | grep AUDIO_CODEC`"
  13. if [ -z "${ACODECS}" ]; then
  14. echo "`basename "${0}"`: Could not determine audio codec" 1>&2
  15. exit 2
  16. fi
  17. VCODECS="`echo "${INFO}" | grep VIDEO_CODEC`"
  18. if [ -z "${VCODECS}" ]; then
  19. echo "`basename "${0}"`: Could not determine video codec" 1>&2
  20. exit 2
  21. fi
  22. # Exclude files with DTS soundtracks or MPEG-1/2 streams
  23. if echo "${ACODECS}" | grep -q ffdca; then
  24. exit 1
  25. elif echo "${VCODECS}" | grep -q ffmpeg[12]; then
  26. exit 1
  27. fi
  28. # Construct the output file name
  29. if [ -z "${outFile}" ]; then
  30. # Use the input file name with a .mov extension
  31. outFile="`basename "${inFile}"`"
  32. outFile="`echo "${outFile}" | sed 's%\.[A-Za-z0-9]*$%%'`"
  33. outFile="`dirname "${inFile}"`/${outFile}"
  34. fi
  35. # Convert to MKV
  36. tmpFile="`mktemp -t toMKV`"
  37. outFile="${outFile}.mkv"
  38. mkvmerge -o "${tmpFile}" "${inFile}"
  39. # Check for errors
  40. if [ ! -e "${tmpFile}" ] || [ `stat -f '%z' "${tmpFile}"` -lt 1000 ]; then
  41. echo "`basename "${0}"`: Error creating output file for input: ${inFile}" 1>&2
  42. # Try to recode (with Handbrake/ffmpeg) if mkvmerge fails
  43. echo "`basename "${0}"`: Attempting recode instead..." 1>&2
  44. ~/bin/video/recode "${inFile}"
  45. exit "${?}"
  46. fi
  47. # Move into place, dropping the original
  48. tmpOut="`mktemp "${outFile}.XXXXXXXX"`"
  49. cp -X "${tmpFile}" "${tmpOut}" && rm "${inFile}" && mv "${tmpOut}" "${outFile}"
  50. rm -f "${tmpFile}"
  51. # Exit cleanly
  52. exit 0