toMKV.sh 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. # Merge external subtitles, if they exist
  36. srtFile="`echo "${inFile}" | sed 's%\.[^\.]*$%%'`.srt"
  37. if [ ! -e "${srtFile}" ]; then
  38. srtFile=""
  39. fi
  40. # Convert to MKV
  41. tmpFile="`mktemp -t toMKV`"
  42. outFile="${outFile}.mkv"
  43. mkvmerge --quiet -o "${tmpFile}" "${inFile}" ${srtFile}
  44. # Check for errors
  45. if [ ! -e "${tmpFile}" ] || [ `stat -f '%z' "${tmpFile}"` -lt 1000 ]; then
  46. echo "`basename "${0}"`: Error creating output file for input: ${inFile}" 1>&2
  47. # Try to recode (with Handbrake/ffmpeg) if mkvmerge fails
  48. echo "`basename "${0}"`: Attempting recode instead..." 1>&2
  49. ~/bin/video/recode "${inFile}"
  50. exit "${?}"
  51. fi
  52. # Move into place, dropping the original
  53. tmpOut="`mktemp "${outFile}.XXXXXXXX"`"
  54. cp -X "${tmpFile}" "${tmpOut}" && rm "${inFile}" && mv "${tmpOut}" "${outFile}"
  55. rm -f "${tmpFile}" "${srtFile}"
  56. # Exit cleanly
  57. exit 0