encode.pl 18 KB

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