encode.pl 17 KB

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