encode.pl 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828
  1. #!/usr/bin/perl
  2. use strict;
  3. use warnings;
  4. # Includes
  5. use IPC::Open3;
  6. use File::Basename;
  7. # Default configuration
  8. my $FORMAT = 'mp4';
  9. my $AUDIO_BITRATE = 192;
  10. my $QUALITY = 20;
  11. my $HD_QUALITY = 22;
  12. my $AUDIO_COPY = 0;
  13. my $STEREO_ONLY = 0;
  14. my $VIDEO_ONLY = 0;
  15. my $HEIGHT = undef();
  16. my $WIDTH = undef();
  17. my $AUDIO_EXCLUDE_REGEX = '\b(?:Chinese|Deutsch|Espanol|Francais|Japanese|Korean|Portugues|Thai)\b';
  18. my $SUB_INCLUDE_REGEX = '\b(?:English|Unknown|Closed\s+Captions)\b';
  19. my $FORCE_MP4 = 0;
  20. my $OUT_DIR = undef();
  21. my $MIXDOWN_CODEC = 'AAC';
  22. my $MIXDOWN_CHANNELS = 2.0;
  23. # Applicaton configuration
  24. my $HD_WIDTH = 1350;
  25. my $MIN_VIDEO_WIDTH = 100;
  26. my $MAX_CROP_DIFF = .1;
  27. my $MAX_DURA_DIFF = 5;
  28. my @CODEC_ORDER = ('DTS-HD', 'DTS', 'PCM', 'AC3', $MIXDOWN_CODEC, 'OTHER');
  29. my %LANG_INCLUDE_ISO = ('639-1' => 1);
  30. my $HB_EXEC = $ENV{'HOME'} . '/bin/video/HandBrakeCLI';
  31. my $DEBUG = 0;
  32. # General parameters for HandBrake
  33. my @video_params = ('--markers', '--large-file', '--optimize', '--encoder', 'x264', '--detelecine', '--decomb', '--loose-anamorphic', '--modulus', '16', '--encopts', 'b-adapt=2:rc-lookahead=50');
  34. my @audio_params = ('--audio-copy-mask', 'dtshd,dts,ac3,aac', '--audio-fallback', 'ffac3');
  35. # Runtime debug mode
  36. if (defined($ENV{'DEBUG'}) && $ENV{'DEBUG'}) {
  37. $DEBUG = 1;
  38. }
  39. # Shortcut config
  40. if ($ENV{'MOBILE'}) {
  41. $ENV{'QUALITY'} = 24;
  42. $ENV{'HEIGHT'} = 720;
  43. $ENV{'WIDTH'} = 1280;
  44. $ENV{'AUDIO_BITRATE'} = 128;
  45. $ENV{'STEREO_ONLY'} = 1;
  46. }
  47. # Allow overrides for audio languages
  48. if ($ENV{'AUDIO_EXCLUDE_REGEX'}) {
  49. $AUDIO_EXCLUDE_REGEX = $ENV{'AUDIO_EXCLUDE_REGEX'};
  50. }
  51. # Allow overrides for subtitle languages
  52. if ($ENV{'SUB_INCLUDE_REGEX'}) {
  53. $SUB_INCLUDE_REGEX = $ENV{'SUB_INCLUDE_REGEX'};
  54. }
  55. # Allow copy-only audio transfers (for use in re-encoding)
  56. if ($ENV{'AUDIO_COPY'}) {
  57. $AUDIO_COPY = 1;
  58. }
  59. # Allow AAC-only audio transfers (for use in mobile encoding)
  60. if ($ENV{'STEREO_ONLY'}) {
  61. $STEREO_ONLY = 1;
  62. }
  63. # Allow video-only transfers
  64. if ($ENV{'VIDEO_ONLY'}) {
  65. $VIDEO_ONLY = 1;
  66. }
  67. # Allow MP4-only output format (for use in mobile encoding)
  68. if ($ENV{'FORCE_MP4'}) {
  69. $FORCE_MP4 = 1;
  70. }
  71. # Allow overrides for video quality
  72. if ($ENV{'QUALITY'}) {
  73. $QUALITY = $ENV{'QUALITY'};
  74. $HD_QUALITY = $ENV{'QUALITY'};
  75. }
  76. # Allow overrides for audio bitrate
  77. if ($ENV{'AUDIO_BITRATE'}) {
  78. $AUDIO_BITRATE = $ENV{'AUDIO_BITRATE'};
  79. }
  80. # Use an alternate output directory, if specified
  81. if ($ENV{'OUT_DIR'}) {
  82. $OUT_DIR = $ENV{'OUT_DIR'};
  83. $OUT_DIR =~ s/\/+$//;
  84. }
  85. # Allow overrides for video height and width. The default is "same as source".
  86. if ($ENV{'HEIGHT'}) {
  87. push(@video_params, '--maxHeight', $ENV{'HEIGHT'});
  88. }
  89. if ($ENV{'WIDTH'}) {
  90. push(@video_params, '--maxWidth', $ENV{'WIDTH'});
  91. }
  92. # Additional arguments for HandBrake, to allow options not supported directly by this script
  93. # Split on spaces; if you need spaces you'll have to work out something else
  94. if ($ENV{'HANDBRAKE_ARGS'}) {
  95. my @args = split(/\s+/, $ENV{'HANDBRAKE_ARGS'});
  96. push(@video_params, @args);
  97. }
  98. # Command-line parameters
  99. my ($in_file, $out_file, $title) = @ARGV;
  100. if (!defined($in_file) || length($in_file) < 1 || !-r $in_file) {
  101. die('Usage: ' . basename($0) . " in_file [out_file] [title]\n");
  102. }
  103. # Sanity checks
  104. if ($AUDIO_COPY && $STEREO_ONLY) {
  105. die(basename($0) . ": AUDIO_COPY and STEREO_ONLY are mutually exclusive\n");
  106. }
  107. if ($VIDEO_ONLY && ($AUDIO_COPY || $STEREO_ONLY)) {
  108. die(basename($0) . ": VIDEO_ONLY and AUDIO_COPY or STEREO_ONLY are mutually exclusive\n");
  109. }
  110. # Scan for title/track info
  111. my %titles = &scan($in_file);
  112. # Allow external subtitles for single-title files
  113. if (scalar(keys(%titles)) == 1) {
  114. my $srt_file = $in_file;
  115. $srt_file =~ s/\.\w{2,4}$/.srt/;
  116. if (!-r $srt_file) {
  117. $srt_file =~ s/\.\w{2,4}$/.ssa/;
  118. }
  119. if (-r $srt_file) {
  120. if ($DEBUG) {
  121. print STDERR 'Adding subtitles from: ' . $srt_file . "\n";
  122. }
  123. push(@video_params, '--srt-file', $srt_file);
  124. }
  125. }
  126. # Allow encoding of a specific title
  127. if ($title) {
  128. if ($title =~ /^\d+$/ && $title > 0) {
  129. if (!defined($titles{$title})) {
  130. die(basename($0) . ': Invalid title number: ' . $title . "\n");
  131. }
  132. my $selected_title = $titles{$title};
  133. %titles = ();
  134. $titles{$title} = $selected_title;
  135. } elsif ($title =~ /main/i) {
  136. my $max_title = 0;
  137. my $max_duration = 0;
  138. foreach my $title (keys(%titles)) {
  139. if (!$titles{$title}{'duration'}) {
  140. warn(basename($0) . ': Unknown duration for title: ' . $title . "\n");
  141. next;
  142. }
  143. my $new_max = 0;
  144. if (abs($titles{$title}{'duration'} - $max_duration) < $MAX_DURA_DIFF) {
  145. if ($titles{$title}{'aspect'} > $titles{$max_title}{'aspect'}) {
  146. $new_max = 1;
  147. } elsif ($titles{$title}{'size'}[0] > $titles{$max_title}{'size'}[0] || $titles{$title}{'size'}[1] > $titles{$max_title}{'size'}[1]) {
  148. $new_max = 1;
  149. }
  150. } elsif ($titles{$title}{'duration'} > $max_duration) {
  151. $new_max = 1;
  152. }
  153. if ($new_max) {
  154. $max_duration = $titles{$title}{'duration'};
  155. $max_title = $title;
  156. }
  157. }
  158. my $selected_title = $titles{$max_title};
  159. %titles = ();
  160. $titles{$max_title} = $selected_title;
  161. }
  162. }
  163. # Ensure we have an output file name
  164. # Force MKV output if the output file name is provided and ends in .MKV
  165. if (!defined($out_file) || length($out_file) < 1) {
  166. $out_file = $in_file;
  167. } else {
  168. my ($force_format) = $out_file =~ /\.(\w{2,4})$/;
  169. if (defined($force_format) && lc($force_format) eq 'mkv') {
  170. $FORMAT = 'mkv';
  171. }
  172. }
  173. # Override the output directory, if requested
  174. if ($OUT_DIR) {
  175. $out_file = $OUT_DIR . '/' . basename($out_file);
  176. }
  177. # Keep copies of our defaults so we can reset between tracks
  178. my $format_default = $FORMAT;
  179. # Encode each title
  180. foreach my $title (keys(%titles)) {
  181. if ($DEBUG) {
  182. print STDERR 'Setting options for title: ' . $title . "\n";
  183. }
  184. # Reset
  185. $FORMAT = $format_default;
  186. # Select a title
  187. my $scan = $titles{$title};
  188. # Skip tracks that have no video
  189. if (scalar(@{ $scan->{'size'} }) < 2 || $scan->{'size'}[0] < $MIN_VIDEO_WIDTH) {
  190. print STDERR basename($0) . ': No video detected in: ' . $in_file . ':' . $title . ". Skipping title...\n";
  191. next;
  192. }
  193. # Parse subtitle tracks
  194. my @subs = &subOptions($scan);
  195. # Parse audio tracks, unless we're in VIDEO_ONLY mode
  196. my @audio = ();
  197. if (!$VIDEO_ONLY) {
  198. @audio = &audioOptions($scan);
  199. # Skip tracks that have no audio
  200. if (scalar(@{ $scan->{'audio'} }) < 1 || scalar(@audio) < 1) {
  201. print STDERR basename($0) . ': No audio detected in: ' . $in_file . ':' . $title . ". Skipping title...\n";
  202. next;
  203. }
  204. # Set the bitrate for transcoded audio tracks
  205. push(@audio, '--ab', $AUDIO_BITRATE);
  206. }
  207. # Set the video quality, using $HD_QUALITY for images larger than $HD_WIDTH (to allow lower quality on HD streams)
  208. my $title_quality = $QUALITY;
  209. if ($scan->{'size'}[0] > $HD_WIDTH) {
  210. $title_quality = $HD_QUALITY;
  211. }
  212. # Override unlikely autocrop values
  213. if ( abs($scan->{'crop'}[0] - $scan->{'crop'}[1]) > $scan->{'size'}[0] * $MAX_CROP_DIFF
  214. || abs($scan->{'crop'}[2] - $scan->{'crop'}[3]) > $scan->{'size'}[0] * $MAX_CROP_DIFF)
  215. {
  216. print STDERR basename($0) . ': Overriding unlikely autocrop values: ' . join(':', @{ $scan->{'crop'} }) . "\n";
  217. my @crop = (0, 0, 0, 0);
  218. $scan->{'crop'} = \@crop;
  219. }
  220. # Force MKV muxing if the output contains PGS subtitles (there's no support in the MP4 muxer)
  221. foreach my $track (values(%{ $scan->{'subtitle_selected'} })) {
  222. if ($track->{'type'} eq 'PGS') {
  223. $FORMAT = 'mkv';
  224. last;
  225. }
  226. }
  227. # Force MKV muxing if the output contains DTS audio (technically MP4 is supported buy QuickTime hates it)
  228. foreach my $track (values(%{ $scan->{'audio_selected'} })) {
  229. if ($track->{'codec'} =~ /DTS/i) {
  230. $FORMAT = 'mkv';
  231. last;
  232. }
  233. }
  234. # Select a file name extension that matches the format
  235. my $title_out_file = $out_file;
  236. $title_out_file =~ s/\.(?:\w{2,4}|dvdmedia)$//i;
  237. if ($FORMAT eq 'mkv') {
  238. $title_out_file .= '.mkv';
  239. } else {
  240. $title_out_file .= '.m4v';
  241. }
  242. # Force the title number into the output file name if there are multiple titles to be encoded
  243. if (scalar(keys(%titles)) > 1) {
  244. my $title_text = sprintf('%02d', $title);
  245. $title_out_file =~ s/(\.\w{2,4})$/\-${title_text}${1}/;
  246. }
  247. # Output file
  248. if (uc($title_out_file) eq uc($in_file)) {
  249. $title_out_file =~ s/(\.\w{2,4})$/-recode${1}/;
  250. }
  251. # Build the arugment list
  252. my @args = ($HB_EXEC);
  253. push(@args, '--title', $title);
  254. push(@args, '--input', $in_file);
  255. push(@args, '--output', $title_out_file);
  256. push(@args, '--format', $FORMAT);
  257. push(@args, '--quality', $title_quality);
  258. push(@args, '--crop', join(':', @{ $scan->{'crop'} }));
  259. push(@args, @video_params);
  260. push(@args, @subs);
  261. # Include audio unless specifically excluded
  262. if (!$VIDEO_ONLY) {
  263. push(@args, @audio_params);
  264. push(@args, @audio);
  265. }
  266. if ($DEBUG) {
  267. print STDERR "\n" . join(' ', @args) . "\n\n";
  268. }
  269. # Sanity check
  270. if (-e $title_out_file) {
  271. print STDERR basename($0) . ': Output file exists: ' . $title_out_file . ". Skipping...\n";
  272. next;
  273. }
  274. # Run it
  275. my $child_out = '';
  276. my $child_in = '';
  277. my $pid = open3($child_in, $child_out, $child_out, @args);
  278. close($child_in);
  279. while (<$child_out>) {
  280. if ($DEBUG) {
  281. print STDERR $_;
  282. }
  283. }
  284. waitpid($pid, 0);
  285. close($child_out);
  286. # Provide the new file name if requested
  287. if ($ENV{'RECODE_OUTFILE'}) {
  288. print $title_out_file;
  289. }
  290. }
  291. # Cleanup
  292. exit(0);
  293. sub subOptions($) {
  294. my ($scan) = @_;
  295. my %tracks = ();
  296. foreach my $track (@{ $scan->{'subtitle'} }) {
  297. 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;
  298. if (!defined($iso)) {
  299. print STDERR 'Could not parse subtitle description: ' . $track->{'description'} . "\n";
  300. next;
  301. }
  302. # Map text/bitmap into a boolean
  303. if ($text =~ /TEXT/i) {
  304. $text = 1;
  305. } else {
  306. $text = 0;
  307. }
  308. # Standardize the codes
  309. $iso = uc($iso);
  310. $type = uc($type);
  311. # Push all parsed data into an array
  312. my %data = ('language' => $language, 'note' => $note, 'iso' => $iso, 'text' => $text, 'type' => $type);
  313. $tracks{ $track->{'index'} } = \%data;
  314. # Print what we found
  315. if ($DEBUG) {
  316. print STDERR 'Found subtitle track: ';
  317. printHash(\%data);
  318. }
  319. }
  320. # Push the parsed data back up the chain
  321. $scan->{'subtitle_parsed'} = \%tracks;
  322. # Select the subtitle tracks we want to keep
  323. my @keep = ();
  324. foreach my $index (keys(%tracks)) {
  325. # Skip PGS tracks when we're forcing MP4 output (they're not allowed by the muxer)
  326. if ($FORCE_MP4 && $tracks{$index}->{'type'} eq 'PGS') {
  327. next;
  328. }
  329. # Keep tracks in our prefered language, and all text-based subtitles (they're small)
  330. if (isValidSubLanguage($tracks{$index}->{'language'}, $tracks{$index}->{'iso'})) {
  331. push(@keep, $index);
  332. } elsif ($tracks{$index}->{'text'}) {
  333. push(@keep, $index);
  334. } else {
  335. if ($DEBUG) {
  336. print STDERR 'Skipping subtitle ' . $index . ' due to language: ' . $tracks{$index}->{'language'} . "\n";
  337. }
  338. }
  339. }
  340. # Push the selected tracks back up the chain
  341. my %tmp = ();
  342. foreach my $num (@keep) {
  343. $tmp{$num} = $tracks{$num};
  344. }
  345. $scan->{'subtitle_selected'} = \%tmp;
  346. # Send back the argument string (if any)
  347. if (scalar(@keep) < 1) {
  348. return '';
  349. }
  350. return ('--subtitle', join(',', @keep));
  351. }
  352. sub audioOptions($) {
  353. my ($scan) = @_;
  354. my @retval = ();
  355. # Type the audio tracks
  356. my %tracks = ();
  357. foreach my $track (@{ $scan->{'audio'} }) {
  358. my ($language, $codec, $note, $channels, $iso, $specs) = $track->{'description'} =~ /^([^\(]+)\s+\(([^\)]+)\)\s+(?:\(([^\)]*Commentary[^\)]*)\)\s+)?\((\d+\.\d+\s+ch|Dolby\s+Surround)\)(?:\s+\(iso(\d+\-\d+)\:\s+\w\w\w\))?(?:,\s+(.*))?/;
  359. if (!defined($channels)) {
  360. print STDERR 'Could not parse audio description: ' . $track->{'description'} . "\n";
  361. next;
  362. }
  363. # Decode the channels string to a number
  364. if ($channels =~ /(\d+\.\d+)\s+ch/i) {
  365. $channels = $1;
  366. } elsif ($channels =~ /Dolby\s+Surround/i) {
  367. $channels = 3.1;
  368. }
  369. # Standardize the codec
  370. foreach my $code (@CODEC_ORDER) {
  371. my $metacode = quotemeta($code);
  372. if ($codec =~ /${metacode}/i) {
  373. $codec = $code;
  374. last;
  375. } elsif ($code eq 'OTHER') {
  376. if ($codec =~ /MP3/i || $codec =~ /MPEG/i) {
  377. $codec = $code;
  378. } elsif ($codec eq 'dca') {
  379. print STDERR 'Found incompatible audio (' . $track->{'description'} . ') in track ' . $track->{'index'} . "\n";
  380. $codec = undef();
  381. } else {
  382. print STDERR 'Found unknown audio (' . $track->{'description'} . ') in track ' . $track->{'index'} . "\n";
  383. $codec = $code;
  384. }
  385. }
  386. }
  387. # Standardize the specs
  388. my $bitrate = 0;
  389. my $samplerate = 0;
  390. if (!$specs) {
  391. $specs = '';
  392. }
  393. if ($specs =~ /(\d+)bps/) {
  394. $bitrate = $1 / 1000;
  395. } elsif ($specs =~ /(\d+)\s*kb\/s/) {
  396. $bitrate = $1;
  397. }
  398. if ($specs =~ /(\d+)Hz/) {
  399. $samplerate = $1;
  400. }
  401. # Push all parsed data into the array
  402. my %data = (
  403. 'language' => $language,
  404. 'codec' => $codec,
  405. 'channels' => $channels,
  406. 'iso' => $iso,
  407. 'note' => $note,
  408. 'bitrate' => $bitrate,
  409. 'samplerate' => $samplerate,
  410. );
  411. $tracks{ $track->{'index'} } = \%data;
  412. # Print what we found
  413. if ($DEBUG) {
  414. print STDERR 'Found audio track: ';
  415. printHash(\%data);
  416. }
  417. }
  418. # Push the parsed data back up the chain
  419. $scan->{'audio_parsed'} = \%tracks;
  420. # Find the track with the most channels for each codec, and the highest number of channels among all types of tracks
  421. # Then choose the most desired codec among the set of codecs that contain the highest number of channels
  422. # This chooses the track with the most channels for the mixdown, and resolves ties using CODEC_ORDER
  423. my $mixdown = undef();
  424. my %bestByCodec = ();
  425. my $bestCodec = undef();
  426. my $mostChannels = 0;
  427. # Loop point, in case we need to run the selector more than once
  428. SELECT_AUDIO:
  429. foreach my $codec (@CODEC_ORDER) {
  430. $bestByCodec{$codec} = findBestAudioTrack(\%tracks, $codec);
  431. if (defined($bestByCodec{$codec}) && (!defined($bestCodec) || $mostChannels < $tracks{ $bestByCodec{$codec} }->{'channels'})) {
  432. $bestCodec = $codec;
  433. $mostChannels = $tracks{ $bestByCodec{$codec} }->{'channels'};
  434. }
  435. }
  436. foreach my $codec (@CODEC_ORDER) {
  437. if (defined($bestByCodec{$codec}) && $tracks{ $bestByCodec{$codec} }->{'channels'} == $mostChannels) {
  438. $mixdown = $bestByCodec{$codec};
  439. last;
  440. }
  441. }
  442. # Sanity check
  443. if (!defined($mixdown) || $mixdown < 1) {
  444. # If we applied an exclude filter, remove it and try again
  445. if ($AUDIO_EXCLUDE_REGEX ne 'ACCEPT_ALL') {
  446. $AUDIO_EXCLUDE_REGEX = 'ACCEPT_ALL';
  447. print STDERR "No usable audio tracks found in title. Removing exclude filter...\n";
  448. goto SELECT_AUDIO;
  449. }
  450. # If we got no audio, give up -- this file is not valid
  451. print STDERR basename($0) . ": No usable audio tracks in title\n";
  452. return;
  453. }
  454. # Clear the mixdown selection if we're copying audio
  455. if ($AUDIO_COPY) {
  456. $mixdown = undef();
  457. }
  458. # Mixdown track first
  459. my @audio_tracks = ();
  460. if (defined($mixdown) && $mixdown > 0) {
  461. if ($DEBUG) {
  462. print STDERR 'Using track ' . $mixdown . " as default AAC audio\n";
  463. if ($tracks{$mixdown}->{'channels'} > 2) {
  464. push(@retval, '--mixdown', 'dpl2');
  465. print STDERR "\tMixing down with Dolby Pro Logic II encoding\n";
  466. }
  467. }
  468. my %track = ('index' => $mixdown, 'encoder' => 'ca_aac');
  469. push(@audio_tracks, \%track);
  470. }
  471. # Keep all other audio tracks, unless STEREO_ONLY is set
  472. if (!$STEREO_ONLY) {
  473. # Passthru DTS-MA, DTS, AC3, and AAC
  474. # Keep other audio tracks, but recode to AAC (using Handbrake's audio-copy-mask/audio-fallback feature)
  475. foreach my $index (keys(%tracks)) {
  476. if (defined($mixdown) && $mixdown == $index && $tracks{$index}->{'channels'} <= $MIXDOWN_CHANNELS) {
  477. if ($DEBUG) {
  478. print STDERR 'Skipping passthru of track ' . $index . ' since it is already used as the mixdown track and contains only ' . $tracks{$index}->{'channels'} . " channels\n";
  479. }
  480. next;
  481. } elsif (!$tracks{$index}->{'codec'}) {
  482. if ($DEBUG) {
  483. print STDERR 'Skipping track ' . $index . " due to invalid codec\n";
  484. }
  485. next;
  486. } elsif (!isValidAudioLanguage($tracks{$index}->{'language'}, $tracks{$index}->{'iso'})) {
  487. if ($DEBUG) {
  488. print STDERR 'Skipping track ' . $index . ' due to language: ' . $tracks{$index}->{'language'} . "\n";
  489. }
  490. next;
  491. } else {
  492. my %track = ('index' => $index, 'encoder' => 'copy');
  493. push(@audio_tracks, \%track);
  494. }
  495. }
  496. }
  497. # Push the selected tracks back up the chain
  498. my %sel = ();
  499. foreach my $track (@audio_tracks) {
  500. # Copy the data, rather than just point to it -- we sometimes need modifications
  501. my $index = $track->{'index'};
  502. my %tmp = %{ $tracks{$index} };
  503. # The mixdown track needs special handling -- it appears twice, and with different settings
  504. if ($track->{'encoder'} ne 'copy' && defined($mixdown) && $mixdown > 0 && $track->{'index'} == $mixdown) {
  505. $index .= '_mixdown';
  506. $tmp{'codec'} = $MIXDOWN_CODEC;
  507. $tmp{'channels'} = $MIXDOWN_CHANNELS;
  508. }
  509. # Collect our (possibly modified) hash
  510. $sel{$index} = \%tmp;
  511. }
  512. $scan->{'audio_selected'} = \%sel;
  513. # Consolidate from the hashes
  514. my @output_tracks = ();
  515. my @output_encoders = ();
  516. foreach my $track (@audio_tracks) {
  517. push(@output_tracks, $track->{'index'});
  518. push(@output_encoders, $track->{'encoder'});
  519. }
  520. # Send back the argument strings
  521. push(@retval, '--audio', join(',', @output_tracks));
  522. push(@retval, '--aencoder', join(',', @output_encoders));
  523. return (@retval);
  524. }
  525. sub scan($) {
  526. my ($in_file) = @_;
  527. # Fork to scan the file
  528. my $child_out = '';
  529. my $pid = open3('<&STDIN', $child_out, $child_out, $HB_EXEC, '--previews', '30', '--title', '0', '--input', $in_file);
  530. # Loop through the output
  531. my $scan;
  532. my %titles = ();
  533. my $inTitle = 0;
  534. my $zone = '';
  535. while (<$child_out>) {
  536. if (!$inTitle && m/scan thread found (\d+) valid title/i) {
  537. if ($DEBUG) {
  538. print STDERR 'Found ' . $1 . " titles in source\n";
  539. }
  540. } elsif (m/^\s+Stream \#0\.(\d+)\(\w+\)\:\s+(.*)/) {
  541. my $stream = $1;
  542. my $desc = $2;
  543. } elsif (m/^\s*\+\s+title\s+(\d+)\:/) {
  544. # Save the current title (if any)
  545. if ($inTitle) {
  546. $titles{$inTitle} = $scan;
  547. }
  548. # Grab the new title number
  549. $inTitle = $1;
  550. # Init the data collectors
  551. my @audio = ();
  552. my @crop = ();
  553. my @subtitle = ();
  554. my @size = ();
  555. my %tmp = (
  556. 'audio' => \@audio,
  557. 'crop' => \@crop,
  558. 'subtitle' => \@subtitle,
  559. 'size' => \@size,
  560. 'duration' => 0,
  561. 'aspect' => 0
  562. );
  563. $scan = \%tmp;
  564. if ($DEBUG) {
  565. print STDERR 'Found data for title ' . $1 . "\n";
  566. }
  567. } elsif ($inTitle) {
  568. if (/^\s*\+\s+size: (\d+)x(\d+)/) {
  569. push(@{ $scan->{'size'} }, $1, $2);
  570. if ($DEBUG) {
  571. print STDERR 'Size: ' . join('x', @{ $scan->{'size'} }) . "\n";
  572. }
  573. if (/\s+display aspect\: (\d*\.\d+)/) {
  574. $scan->{'aspect'} = $1;
  575. if ($DEBUG) {
  576. print STDERR 'Aspect: ' . $scan->{'aspect'} . "\n";
  577. }
  578. }
  579. } elsif (/^\s*\+\s+duration\:\s+(\d+)\:(\d+)\:(\d+)/) {
  580. $scan->{'duration'} = ($1 * 3600) + ($2 * 60) + $3;
  581. if ($DEBUG) {
  582. print STDERR 'Duration: ' . $scan->{'duration'} . "\n";
  583. }
  584. } elsif (/^\s*\+\s+autocrop\:\s+(\d+)\/(\d+)\/(\d+)\/(\d+)/) {
  585. push(@{ $scan->{'crop'} }, $1, $2, $3, $4);
  586. if ($DEBUG) {
  587. print STDERR 'Crop: ' . join('/', @{ $scan->{'crop'} }) . "\n";
  588. }
  589. } elsif ($zone ne 'audio' && /^\s*\+\s+audio\s+tracks\:\s*$/) {
  590. $zone = 'audio';
  591. } elsif ($zone eq 'audio' && /^\s*\+\s+(\d+)\,\s+(.*)/) {
  592. my %track = ('index' => $1, 'description' => $2);
  593. push(@{ $scan->{'audio'} }, \%track);
  594. if ($DEBUG) {
  595. print STDERR 'Audio Track #' . $track{'index'} . ': ' . $track{'description'} . "\n";
  596. }
  597. } elsif ($zone ne 'subtitle' && /^\s*\+\s+subtitle\s+tracks\:\s*$/) {
  598. $zone = 'subtitle';
  599. } elsif ($zone eq 'subtitle' && m/^\s*\+\s+(\d+)\,\s+(.*)$/) {
  600. my %track = ('index' => $1, 'description' => $2);
  601. push(@{ $scan->{'subtitle'} }, \%track);
  602. if ($DEBUG) {
  603. print STDERR 'Subtitle Track #' . $track{'index'} . ': ' . $track{'description'} . "\n";
  604. }
  605. }
  606. }
  607. }
  608. # Save the last title (if any)
  609. if ($inTitle) {
  610. $titles{$inTitle} = $scan;
  611. }
  612. # Cleanup the scan process
  613. waitpid($pid, 0);
  614. close($child_out);
  615. # Sanity check
  616. if (scalar(keys(%titles)) < 1) {
  617. die(basename($0) . ': Did not find any titles in file: ' . $in_file . "\n");
  618. }
  619. # Return
  620. return %titles;
  621. }
  622. sub findBestAudioTrack($$) {
  623. my ($tracks, $codec) = @_;
  624. my $best = undef();
  625. my @available = ();
  626. # Find available tracks
  627. for my $index (keys(%{$tracks})) {
  628. my $track = $tracks->{$index};
  629. # Skip tracks not in the specified codec
  630. if (!$track->{'codec'} || $track->{'codec'} ne $codec) {
  631. next;
  632. }
  633. # Skip foreign language tracks
  634. if (!isValidAudioLanguage($track->{'language'}, $track->{'iso'})) {
  635. next;
  636. }
  637. push(@available, $index);
  638. }
  639. if (scalar(@available) < 1) {
  640. return $best;
  641. }
  642. # Find the tracks with the most channels
  643. {
  644. my @most = ();
  645. my $channels = 0;
  646. foreach my $index (@available) {
  647. my $track = $tracks->{$index};
  648. if ($track->{'channels'} > $channels) {
  649. @most = ($index);
  650. $channels = $track->{'channels'};
  651. } elsif ($track->{'channels'} == $channels) {
  652. push(@most, $index);
  653. }
  654. }
  655. @available = @most;
  656. }
  657. if (scalar(@available) < 1) {
  658. return $best;
  659. }
  660. # Find the tracks with the highest bitrate
  661. {
  662. my @highest = ();
  663. my $bitrate = 0;
  664. foreach my $index (@available) {
  665. my $track = $tracks->{$index};
  666. if ($track->{'bitrate'} > $bitrate) {
  667. @highest = ($index);
  668. $bitrate = $track->{'bitrate'};
  669. } elsif ($track->{'bitrate'} == $bitrate) {
  670. push(@highest, $index);
  671. }
  672. }
  673. @available = @highest;
  674. }
  675. if (scalar(@available) < 1) {
  676. return $best;
  677. }
  678. # Find the track if the lowest index
  679. foreach my $index (@available) {
  680. if (!defined($best) || $index < $best) {
  681. $best = $index;
  682. }
  683. }
  684. return $best;
  685. }
  686. sub isValidSubLanguage($) {
  687. my ($lang, $iso) = @_;
  688. if (scalar(keys(%LANG_INCLUDE_ISO)) && $LANG_INCLUDE_ISO{$iso}) {
  689. return 1;
  690. } elsif ($SUB_INCLUDE_REGEX && $lang =~ /${SUB_INCLUDE_REGEX}/i) {
  691. return 1;
  692. }
  693. return 0;
  694. }
  695. sub isValidAudioLanguage($) {
  696. my ($lang, $iso) = @_;
  697. if (scalar(keys(%LANG_INCLUDE_ISO)) && $LANG_INCLUDE_ISO{$iso}) {
  698. return 1;
  699. } elsif ($AUDIO_EXCLUDE_REGEX && $lang =~ /${AUDIO_EXCLUDE_REGEX}/i) {
  700. return 0;
  701. }
  702. return 1;
  703. }
  704. sub printHash($) {
  705. my ($data) = @_;
  706. my $first = 1;
  707. foreach my $key (keys(%{$data})) {
  708. if (defined($data->{$key})) {
  709. if ($first) {
  710. $first = 0;
  711. } else {
  712. print STDERR ', ';
  713. }
  714. print STDERR $key . ' => ' . $data->{$key};
  715. }
  716. }
  717. print STDERR "\n";
  718. }