encode.pl 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  1. #!/usr/bin/perl
  2. use strict;
  3. use warnings;
  4. # Includes
  5. use IPC::Open3;
  6. use File::Basename;
  7. # Parameters
  8. my @video_params = ('--markers', '--large-file', '--optimize', '--encoder', 'x264', '--detelecine', '--decomb', '--loose-anamorphic', '--modulus', '16', '--encopts', 'b-adapt=2:rc-lookahead=50', '--audio-copy-mask', 'dtshd,dts,ac3,aac', '--audio-fallback', 'ca_aac', '--mixdown', 'dpl2', '--ab', '192');
  9. my $FORMAT = 'mp4';
  10. my $QUALITY = 20;
  11. my $HD_QUALITY = 20;
  12. my $HD_WIDTH = 1350;
  13. my $MIN_VIDEO_WIDTH = 100;
  14. my $MAX_CROP_DIFF = .1;
  15. my $MAX_DURA_DIFF = 5;
  16. my @CODEC_ORDER = ('DTS-HD', 'DTS', 'PCM', 'AC3', 'AAC', 'OTHER');
  17. my $AUDIO_EXCLUDE_REGEX = '\b(?:Chinese|Espanol|Francais|Japanese|Korean|Portugues|Thai)\b';
  18. my $SUB_INCLUDE_REGEX = '\b(?:English|Unknown|Closed\s+Captions)\b';
  19. my %LANG_INCLUDE_ISO = ('639-1' => 1);
  20. my $HB_EXEC = $ENV{'HOME'} . '/bin/video/HandBrakeCLI';
  21. my $DEBUG = 0;
  22. # Runtime debug mode
  23. if (defined($ENV{'DEBUG'}) && $ENV{'DEBUG'}) {
  24. $DEBUG = 1;
  25. }
  26. # Command-line parameters
  27. my ($in_file, $out_file, $title) = @ARGV;
  28. if (!defined($in_file) || length($in_file) < 1 || !-r $in_file) {
  29. die('Usage: ' . basename($0) . " in_file [out_file] [title]\n");
  30. }
  31. # Scan for title/track info
  32. my %titles = &scan($in_file);
  33. # Allow external subtitles for single-title files
  34. if (scalar(keys(%titles)) == 1) {
  35. my $srt_file = $in_file;
  36. $srt_file =~ s/\.\w{2,3}$/.srt/;
  37. if (-r $srt_file) {
  38. if ($DEBUG) {
  39. print STDERR 'Adding subtitles from: ' . $srt_file . "\n";
  40. }
  41. push(@video_params, '--srt-file', $srt_file);
  42. }
  43. }
  44. # Allow encoding of a specific title
  45. if ($title) {
  46. if ($title =~ /^\d+$/ && $title > 0) {
  47. if (!defined($titles{$title})) {
  48. die(basename($0) . ': Invalid title number: ' . $title . "\n");
  49. }
  50. my $selected_title = $titles{$title};
  51. %titles = ();
  52. $titles{$title} = $selected_title;
  53. } elsif ($title =~ /main/i) {
  54. my $max_title = 0;
  55. my $max_duration = 0;
  56. foreach my $title (keys(%titles)) {
  57. if (!$titles{$title}{'duration'}) {
  58. warn(basename($0) . ': Unknown duration for title: ' . $title . "\n");
  59. next;
  60. }
  61. my $new_max = 0;
  62. if (abs($titles{$title}{'duration'} - $max_duration) < $MAX_DURA_DIFF) {
  63. if ($titles{$title}{'aspect'} > $titles{$max_title}{'aspect'}) {
  64. $new_max = 1;
  65. } elsif ($titles{$title}{'size'}[0] > $titles{$max_title}{'size'}[0] || $titles{$title}{'size'}[1] > $titles{$max_title}{'size'}[1]) {
  66. $new_max = 1;
  67. }
  68. } elsif ($titles{$title}{'duration'} > $max_duration) {
  69. $new_max = 1;
  70. }
  71. if ($new_max) {
  72. $max_duration = $titles{$title}{'duration'};
  73. $max_title = $title;
  74. }
  75. }
  76. my $selected_title = $titles{$max_title};
  77. %titles = ();
  78. $titles{$max_title} = $selected_title;
  79. }
  80. }
  81. # Ensure we have an output file name
  82. # Allow forced use of MKV wrapper if the output file name is provided and ends in .MKV
  83. if (!defined($out_file) || length($out_file) < 1) {
  84. $out_file = $in_file;
  85. } else {
  86. my ($force_format) = $out_file =~ /\.(\w{2,3})$/;
  87. if (lc($force_format) eq 'mkv') {
  88. $FORMAT = 'mkv';
  89. }
  90. }
  91. # Encode each title
  92. foreach my $title (keys(%titles)) {
  93. if ($DEBUG) {
  94. print STDERR 'Setting options for title: ' . $title . "\n";
  95. }
  96. # Parse the title's audio and subtitle tracks
  97. my $scan = $titles{$title};
  98. my @audio = &audioOptions($scan);
  99. my @subs = &subOptions($scan);
  100. # Skip tracks that have no video
  101. if (scalar(@{ $scan->{'size'} }) < 2 || $scan->{'size'}[0] < $MIN_VIDEO_WIDTH) {
  102. print STDERR basename($0) . ': No video detected in: ' . $in_file . ':' . $title . ". Skipping title...\n";
  103. next;
  104. }
  105. # Skip tracks that have no audio
  106. if (scalar(@{ $scan->{'audio'} }) < 1) {
  107. print STDERR basename($0) . ': No audio detected in: ' . $in_file . ':' . $title . ". Skipping title...\n";
  108. next;
  109. }
  110. # Reduce the quality if the image size is particularly large
  111. my $title_quality = $QUALITY;
  112. if ($scan->{'size'}[0] > $HD_WIDTH) {
  113. $title_quality = $HD_QUALITY;
  114. }
  115. # Override unlikely autocrop values
  116. if ( abs($scan->{'crop'}[0] - $scan->{'crop'}[1]) > $scan->{'size'}[0] * $MAX_CROP_DIFF
  117. || abs($scan->{'crop'}[2] - $scan->{'crop'}[3]) > $scan->{'size'}[0] * $MAX_CROP_DIFF)
  118. {
  119. print STDERR basename($0) . ': Overriding unlikely autocrop values: ' . join(':', @{ $scan->{'crop'} }) . "\n";
  120. my @crop = (0, 0, 0, 0);
  121. $scan->{'crop'} = \@crop;
  122. }
  123. # Select a file name extension that matches the format
  124. my $title_out_file = $out_file;
  125. $title_out_file =~ s/\.(?:\w{2,3}|dvdmedia)$//i;
  126. if ($FORMAT eq 'mkv') {
  127. $title_out_file .= '.mkv';
  128. } else {
  129. $title_out_file .= '.m4v';
  130. }
  131. # Force the title number into the output file name if there are multiple titles to be encoded
  132. if (scalar(keys(%titles)) > 1) {
  133. my $title_text = sprintf('%02d', $title);
  134. $title_out_file =~ s/(\.\w{2,3})$/\-${title_text}${1}/;
  135. }
  136. # Sanity check
  137. if (uc($title_out_file) eq uc($in_file)) {
  138. $title_out_file =~ s/(\.\w{2,3})$/-recode${1}/;
  139. }
  140. if (-e $title_out_file) {
  141. print STDERR basename($0) . ': Output file exists: ' . $title_out_file . ". Skipping...\n";
  142. next;
  143. }
  144. # Build the arugment list
  145. my @args = ($HB_EXEC);
  146. push(@args, '--title', $title);
  147. push(@args, '--input', $in_file);
  148. push(@args, '--output', $title_out_file);
  149. push(@args, '--format', $FORMAT);
  150. push(@args, '--quality', $title_quality);
  151. push(@args, '--crop', join(':', @{ $scan->{'crop'} }));
  152. push(@args, @video_params);
  153. push(@args, @audio);
  154. push(@args, @subs);
  155. # Run it
  156. if ($DEBUG) {
  157. print STDERR join(' ', @args) . "\n";
  158. }
  159. my $child_out = '';
  160. my $child_in = '';
  161. my $pid = open3($child_in, $child_out, $child_out, @args);
  162. close($child_in);
  163. while (<$child_out>) {
  164. if ($DEBUG) {
  165. print STDERR $_;
  166. }
  167. }
  168. waitpid($pid, 0);
  169. close($child_out);
  170. # Provide the new file name if requested
  171. if ($ENV{'RECODE_OUTFILE'}) {
  172. print $title_out_file;
  173. }
  174. }
  175. # Cleanup
  176. exit(0);
  177. sub subOptions($) {
  178. my ($scan) = @_;
  179. my %tracks = ();
  180. foreach my $track (@{ $scan->{'subtitle'} }) {
  181. my ($language, $iso, $text, $type) = $track->{'description'} =~ /^([^\(]+)\s+\(iso(\d+\-\d+)\:\s+\w\w\w\)\s+\((Text|Bitmap)\)\((CC|VOBSUB|PGS)\)/i;
  182. if (!defined($iso)) {
  183. print STDERR 'Could not parse subtitle description: ' . $track->{'description'} . "\n";
  184. # Temporarily exit on parsing errors -- at least until we're sure about this new parser
  185. #next;
  186. exit(1);
  187. }
  188. # Map text/bitmap into a boolean
  189. if ($text =~ /TEXT/i) {
  190. $text = 1;
  191. } else {
  192. $text = 0;
  193. }
  194. # Push all parsed data into an array
  195. my %data = ('language' => $language, 'iso' => $iso, 'text' => $text, 'type' => $type);
  196. $tracks{ $track->{'index'} } = \%data;
  197. # Print what we found
  198. if ($DEBUG) {
  199. print STDERR 'Found subtitle track: ';
  200. printHash(\%data);
  201. }
  202. }
  203. # Keep subtitles in our prefered langauges, and all text-based subtitles (they're small)
  204. my @keep = ();
  205. foreach my $index (keys(%tracks)) {
  206. if (isValidSubLanguage($tracks{$index}->{'language'}, $tracks{$index}->{'iso'})) {
  207. push(@keep, $index);
  208. } elsif ($tracks{$index}->{'text'}) {
  209. push(@keep, $index);
  210. } else {
  211. if ($DEBUG) {
  212. print STDERR 'Skipping subtitle ' . $index . ' due to language: ' . $tracks{$index}->{'language'} . "\n";
  213. }
  214. }
  215. }
  216. # Send back the argument string (if any)
  217. if (scalar(@keep) < 1) {
  218. return '';
  219. }
  220. return ('--subtitle', join(',', @keep));
  221. }
  222. sub audioOptions($) {
  223. my ($scan) = @_;
  224. # Type the audio tracks
  225. my %tracks = ();
  226. foreach my $track (@{ $scan->{'audio'} }) {
  227. my ($language, $codec, $note, $channels, $iso) = $track->{'description'} =~ /^([^\(]+)\s+\(([^\)]+)\)\s+(?:\(([^\)]*Commentary[^\)]*)\)\s+)?\((\d+\.\d+\s+ch|Dolby\s+Surround)\)(?:\s+\(iso(\d+\-\d+)\:\s+\w\w\w\))?/;
  228. if (!defined($channels)) {
  229. print STDERR 'Could not parse audio description: ' . $track->{'description'} . "\n";
  230. # Temporarily exit on parsing errors -- at least until we're sure about this new parser
  231. #next;
  232. exit(1);
  233. }
  234. # Decode the channels string to a number
  235. if ($channels =~ /(\d+\.\d+)\s+ch/i) {
  236. $channels = $1;
  237. } elsif ($channels =~ /Dolby\s+Surround/i) {
  238. $channels = 3.1;
  239. }
  240. # Standardize the codec
  241. foreach my $code (@CODEC_ORDER) {
  242. my $metacode = quotemeta($code);
  243. if ($codec =~ /${metacode}/i) {
  244. $codec = $code;
  245. last;
  246. } elsif ($code eq 'OTHER') {
  247. if (!($codec =~ /MP3/i || $codec =~ /MPEG/i)) {
  248. print STDERR 'Found unknown audio (' . $track->{'description'} . ') in track ' . $track->{'index'} . "\n";
  249. }
  250. $codec = $code;
  251. }
  252. }
  253. # Push all parsed data into the array
  254. my %data = ('language' => $language, 'codec' => $codec, 'channels' => $channels, 'iso' => $iso, 'note' => $note);
  255. $tracks{ $track->{'index'} } = \%data;
  256. # Print what we found
  257. if ($DEBUG) {
  258. print STDERR 'Found audio track: ';
  259. printHash(\%data);
  260. }
  261. }
  262. # Find the track with the most channels for each codec, and the highest number of channels among all types of tracks
  263. # Then choose the most desired codec among the set of codecs that contain the highest number of channels
  264. # This chooses the track with the most channels for the mixdown, and resolves ties using CODEC_ORDER
  265. my $mixdown = undef();
  266. my %bestByCodec = ();
  267. my $bestCodec = undef();
  268. my $mostChannels = 0;
  269. foreach my $codec (@CODEC_ORDER) {
  270. $bestByCodec{$codec} = findBestAudioTrack(\%tracks, $codec);
  271. if (defined($bestByCodec{$codec}) && (!defined($bestCodec) || $mostChannels < $tracks{ $bestByCodec{$codec} }->{'channels'})) {
  272. $bestCodec = $codec;
  273. $mostChannels = $tracks{ $bestByCodec{$codec} }->{'channels'};
  274. }
  275. }
  276. foreach my $codec (@CODEC_ORDER) {
  277. if (defined($bestByCodec{$codec}) && $tracks{ $bestByCodec{$codec} }->{'channels'} == $mostChannels) {
  278. $mixdown = $bestByCodec{$codec};
  279. last;
  280. }
  281. }
  282. # Sanity check
  283. if (!defined($mixdown) || $mixdown < 1) {
  284. print STDERR basename($0) . ": No usable audio tracks in title\n";
  285. return;
  286. }
  287. # Mixdown track first
  288. my @audio_tracks = ();
  289. if (defined($mixdown) && $mixdown > 0) {
  290. if ($DEBUG) {
  291. print STDERR 'Using track ' . $mixdown . " as default AAC audio\n";
  292. if ($tracks{$mixdown}->{'channels'} > 2) {
  293. print STDERR "\tMixing down with Dolby Pro Logic II encoding\n";
  294. }
  295. }
  296. my %track = ('index' => $mixdown, 'encoder' => 'ca_aac');
  297. push(@audio_tracks, \%track);
  298. }
  299. # Passthru DTS-MA, DTS, AC3, and AAC
  300. # Keep other audio tracks, but recode to AAC (using Handbrake's audio-copy-mask/audio-fallback feature)
  301. foreach my $index (keys(%tracks)) {
  302. if ($mixdown == $index && $tracks{$index}->{'codec'} eq 'OTHER' && $tracks{$index}->{'channels'} <= 2) {
  303. if ($DEBUG) {
  304. print STDERR 'Skipping recode of track ' . $index . ' since it is already used as the default track and contains only ' . $tracks{$index}->{'channels'} . " channels\n";
  305. }
  306. next;
  307. } elsif (!isValidAudioLanguage($tracks{$index}->{'language'}, $tracks{$index}->{'iso'})) {
  308. if ($DEBUG) {
  309. print STDERR 'Skipping track ' . $index . ' due to language: ' . $tracks{$index}->{'language'} . "\n";
  310. }
  311. next;
  312. } else {
  313. my %track = ('index' => $index, 'encoder' => 'copy');
  314. push(@audio_tracks, \%track);
  315. }
  316. }
  317. # Consolidate from the hashes
  318. my @output_tracks = ();
  319. my @output_encoders = ();
  320. foreach my $track (@audio_tracks) {
  321. push(@output_tracks, $track->{'index'});
  322. push(@output_encoders, $track->{'encoder'});
  323. }
  324. # Send back the argument strings
  325. return ('--audio', join(',', @output_tracks), '--aencoder', join(',', @output_encoders));
  326. }
  327. sub scan($) {
  328. my ($in_file) = @_;
  329. # Fork to scan the file
  330. my $child_out = '';
  331. my $pid = open3('<&STDIN', $child_out, $child_out, $HB_EXEC, '--title', '0', '--input', $in_file);
  332. # Loop through the output
  333. my $scan;
  334. my %titles = ();
  335. my $inTitle = 0;
  336. my $zone = '';
  337. my $dca_stream = -1;
  338. my %dca_lossless = ();
  339. while (<$child_out>) {
  340. if (!$inTitle && m/scan thread found (\d+) valid title/i) {
  341. if ($DEBUG) {
  342. print STDERR 'Found ' . $1 . " titles in source\n";
  343. }
  344. } elsif (m/^\s+Stream \#0\.(\d+)\(\w+\)\:\s+(.*)/) {
  345. my $stream = $1;
  346. my $desc = $2;
  347. $dca_stream = -1;
  348. if ($desc =~ /Audio\:\s+dca/) {
  349. $dca_stream = $stream;
  350. }
  351. } elsif ($dca_stream >= 0 && m/^\s+title\s*\:\s+(.*)/) {
  352. if ($1 =~ /Lossless/i) {
  353. $dca_lossless{$dca_stream} = 1;
  354. if ($DEBUG) {
  355. print STDERR 'Found DTS Lossless audio in stream: ' . $dca_stream . "\n";
  356. }
  357. }
  358. $dca_stream = -1;
  359. } elsif (m/^\s*\+\s+title\s+(\d+)\:/) {
  360. # Save the current title (if any)
  361. if ($inTitle) {
  362. $titles{$inTitle} = $scan;
  363. }
  364. # Grab the new title number
  365. $inTitle = $1;
  366. # Init the data collectors
  367. my @audio = ();
  368. my @crop = ();
  369. my @subtitle = ();
  370. my @size = ();
  371. my %tmp = (
  372. 'audio' => \@audio,
  373. 'crop' => \@crop,
  374. 'subtitle' => \@subtitle,
  375. 'size' => \@size,
  376. 'duration' => 0,
  377. 'aspect' => 0
  378. );
  379. $scan = \%tmp;
  380. if ($DEBUG) {
  381. print STDERR 'Found data for title ' . $1 . "\n";
  382. }
  383. } elsif ($inTitle) {
  384. if (/^\s*\+\s+size: (\d+)x(\d+)/) {
  385. push(@{ $scan->{'size'} }, $1, $2);
  386. if ($DEBUG) {
  387. print STDERR 'Size: ' . join('x', @{ $scan->{'size'} }) . "\n";
  388. }
  389. if (/\s+display aspect\: (\d*\.\d+)/) {
  390. $scan->{'aspect'} = $1;
  391. if ($DEBUG) {
  392. print STDERR 'Aspect: ' . $scan->{'aspect'} . "\n";
  393. }
  394. }
  395. } elsif (/^\s*\+\s+duration\:\s+(\d+)\:(\d+)\:(\d+)/) {
  396. $scan->{'duration'} = ($1 * 3600) + ($2 * 60) + $3;
  397. if ($DEBUG) {
  398. print STDERR 'Duration: ' . $scan->{'duration'} . "\n";
  399. }
  400. } elsif (/^\s*\+\s+autocrop\:\s+(\d+)\/(\d+)\/(\d+)\/(\d+)/) {
  401. push(@{ $scan->{'crop'} }, $1, $2, $3, $4);
  402. if ($DEBUG) {
  403. print STDERR 'Crop: ' . join('/', @{ $scan->{'crop'} }) . "\n";
  404. }
  405. } elsif ($zone ne 'audio' && /^\s*\+\s+audio\s+tracks\:\s*$/) {
  406. $zone = 'audio';
  407. } elsif ($zone eq 'audio' && /^\s*\+\s+(\d+)\,\s+(.*)/) {
  408. my %track = ('index' => $1, 'description' => $2);
  409. if ($dca_lossless{ $track{'index'} }) {
  410. $track{'description'} =~ s/\(DTS\)/\(DTS-MA\)/;
  411. }
  412. push(@{ $scan->{'audio'} }, \%track);
  413. if ($DEBUG) {
  414. print STDERR 'Audio Track #' . $track{'index'} . ': ' . $track{'description'} . "\n";
  415. }
  416. } elsif ($zone ne 'subtitle' && /^\s*\+\s+subtitle\s+tracks\:\s*$/) {
  417. $zone = 'subtitle';
  418. } elsif ($zone eq 'subtitle' && m/^\s*\+\s+(\d+)\,\s+(.*)$/) {
  419. my %track = ('index' => $1, 'description' => $2);
  420. push(@{ $scan->{'subtitle'} }, \%track);
  421. if ($DEBUG) {
  422. print STDERR 'Subtitle Track #' . $track{'index'} . ': ' . $track{'description'} . "\n";
  423. }
  424. }
  425. }
  426. }
  427. # Save the last title (if any)
  428. if ($inTitle) {
  429. $titles{$inTitle} = $scan;
  430. }
  431. # Cleanup the scan process
  432. waitpid($pid, 0);
  433. close($child_out);
  434. # Sanity check
  435. if (scalar(keys(%titles)) < 1) {
  436. die(basename($0) . ': Did not find any titles in file: ' . $in_file . "\n");
  437. }
  438. # Return
  439. return %titles;
  440. }
  441. sub findBestAudioTrack($$) {
  442. my ($tracks, $codec) = @_;
  443. my $best = undef();
  444. my $channels = 0;
  445. for my $index (keys(%{$tracks})) {
  446. my $track = $tracks->{$index};
  447. # Skip tracks not in the specified codec
  448. if ($track->{'codec'} ne $codec) {
  449. next;
  450. }
  451. # Skip foreign language tracks
  452. if (!isValidAudioLanguage($track->{'language'}, $track->{'iso'})) {
  453. next;
  454. }
  455. # Find the track with the most channels (Ófirst wins)
  456. if (!defined($best) || $track->{'channels'} > $channels) {
  457. $best = $index;
  458. $channels = $track->{'channels'};
  459. }
  460. }
  461. return $best;
  462. }
  463. sub isValidSubLanguage($) {
  464. my ($lang, $iso) = @_;
  465. if (scalar(keys(%LANG_INCLUDE_ISO)) && $LANG_INCLUDE_ISO{$iso}) {
  466. return 1;
  467. } elsif ($SUB_INCLUDE_REGEX && $lang =~ /${SUB_INCLUDE_REGEX}/i) {
  468. return 1;
  469. }
  470. return 0;
  471. }
  472. sub isValidAudioLanguage($) {
  473. my ($lang, $iso) = @_;
  474. if (scalar(keys(%LANG_INCLUDE_ISO)) && $LANG_INCLUDE_ISO{$iso}) {
  475. return 1;
  476. } elsif ($AUDIO_EXCLUDE_REGEX && $lang =~ /${AUDIO_EXCLUDE_REGEX}/i) {
  477. return 0;
  478. }
  479. return 1;
  480. }
  481. sub printHash($) {
  482. my ($data) = @_;
  483. my $first = 1;
  484. foreach my $key (keys(%{$data})) {
  485. if (defined($data->{$key})) {
  486. if ($first) {
  487. $first = 0;
  488. } else {
  489. print STDERR ', ';
  490. }
  491. print STDERR $key . ' => ' . $data->{$key};
  492. }
  493. }
  494. print STDERR "\n";
  495. }