toMKV.sh 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #!/bin/bash
  2. # Defaults
  3. if [ -z "${MIN_AVI_SIZE}" ]; then
  4. MIN_AVI_SIZE=$(( 450 * 1024 * 1024 ))
  5. fi
  6. # Command line
  7. inFile="${1}"
  8. outFile="${2}"
  9. if [ -z "${inFile}" ] || [ ! -e "${inFile}" ]; then
  10. echo "Usage: `basename "${0}"` input_file [output_file]" 1>&2
  11. exit 1
  12. fi
  13. # Grab some codec info
  14. INFO="`~/bin/video/movInfo.pl "${inFile}" 2>/dev/null`"
  15. VCODECS="`echo "${INFO}" | grep VIDEO_CODEC`"
  16. if [ -z "${VCODECS}" ]; then
  17. if echo "${inFile}" | grep -qi '\.avi$' && [ `wc -c < "${inFile}"` -lt $MIN_AVI_SIZE ]; then
  18. echo "Deleting unlikely AVI: ${inFile}" 1>&2
  19. rm -f "${inFile}"
  20. exit 3
  21. fi
  22. echo "`basename "${0}"`: Could not determine video codec" 1>&2
  23. exit 2
  24. fi
  25. # Exclude files with MPEG-1/2 streams
  26. if echo "${VCODECS}" | grep -q ffmpeg[12]; then
  27. echo "Usage: `basename "${0}"` input_file [output_file]" 1>&2
  28. exit 1
  29. fi
  30. # Construct the output file name
  31. if [ -z "${outFile}" ]; then
  32. outFile="`basename "${inFile}"`"
  33. outFile="`echo "${outFile}" | sed 's%\.[A-Za-z0-9]*$%%'`"
  34. outFile="`dirname "${inFile}"`/${outFile}"
  35. fi
  36. # Merge external subtitles, if they exist
  37. srtFile="`echo "${inFile}" | sed 's%\.[^\.]*$%%'`.srt"
  38. if [ ! -e "${srtFile}" ]; then
  39. srtFile="`echo "${inFile}" | sed 's%\.[^\.]*$%%'`.ssa"
  40. fi
  41. if [ ! -e "${srtFile}" ]; then
  42. srtFile=""
  43. fi
  44. # Convert to MKV
  45. # Hide some common AVI conversion warnings
  46. tmpFile="`mktemp -t toMKV`"
  47. outFile="${outFile}.mkv"
  48. if [ -n "${srtFile}" ]; then
  49. OUT="`mkvmerge --quiet --default-language eng -o "${tmpFile}" "${inFile}" "${srtFile}" 2>&1`"
  50. else
  51. OUT="`mkvmerge --quiet --default-language eng -o "${tmpFile}" "${inFile}" 2>&1`"
  52. fi
  53. echo "${OUT}" | grep -v "The AVC video track is missing the 'CTTS' atom for frame timecode offsets."
  54. # Check for errors
  55. if [ ! -e "${tmpFile}" ] || [ `stat -f '%z' "${tmpFile}"` -lt 1000 ]; then
  56. echo "`basename "${0}"`: Error creating output file for input: ${inFile}" 1>&2
  57. # Try to recode (with Handbrake/ffmpeg) if mkvmerge fails
  58. echo "`basename "${0}"`: Attempting recode instead..." 1>&2
  59. ~/bin/video/recode "${inFile}"
  60. exit "${?}"
  61. fi
  62. # Move into place, dropping the original
  63. tmpOut="`mktemp "${outFile}.XXXXXXXX"`"
  64. cp -X "${tmpFile}" "${tmpOut}" && rm "${inFile}" && mv "${tmpOut}" "${outFile}"
  65. rm -f "${tmpFile}" "${srtFile}"
  66. # Exit cleanly
  67. exit 0