toMKV.sh 1.7 KB

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