Turn audio into a shareable video. forked from nypublicradio/audiogram

index.js 8.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. var d3 = require("d3"),
  2. $ = require("jquery"),
  3. preview = require("./preview.js"),
  4. video = require("./video.js"),
  5. audio = require("./audio.js");
  6. d3.json("/settings/labels.json", function(err, labels){
  7. // Populate labels menu
  8. d3.select("#input-label")
  9. .on("change", updateLabel)
  10. .selectAll("option")
  11. .data(labels.podcasts)
  12. .enter()
  13. .append("option")
  14. .text(function(l){
  15. return l;
  16. });
  17. d3.select("#input-label").each(updateLabel);
  18. }); // end label ingestion
  19. d3.json("/settings/themes.json", function(err, themes){
  20. var errorMessage;
  21. // Themes are missing or invalid
  22. if (err || !d3.keys(themes).filter(function(d){ return d !== "default"; }).length) {
  23. if (err instanceof SyntaxError) {
  24. errorMessage = "Error in settings/themes.json:<br/><code>" + err.toString() + "</code>";
  25. } else if (err instanceof ProgressEvent) {
  26. errorMessage = "Error: no settings/themes.json.";
  27. } else if (err) {
  28. errorMessage = "Error: couldn't load settings/themes.json.";
  29. } else {
  30. errorMessage = "No themes found in settings/themes.json.";
  31. }
  32. d3.select("#loading-bars").remove();
  33. d3.select("#loading-message").html(errorMessage);
  34. if (err) {
  35. throw err;
  36. }
  37. return;
  38. }
  39. for (var key in themes) {
  40. themes[key] = $.extend({}, themes.default, themes[key]);
  41. }
  42. preloadImages(themes);
  43. });
  44. function submitted() {
  45. d3.event.preventDefault();
  46. var theme = preview.theme(),
  47. caption = preview.caption(),
  48. citation = preview.citation(),
  49. label = preview.label(),
  50. selection = preview.selection(),
  51. file = preview.file();
  52. if (!file) {
  53. d3.select("#row-audio").classed("error", true);
  54. return setClass("error", "No audio file selected.");
  55. }
  56. if (theme.maxDuration && selection.duration > theme.maxDuration) {
  57. return setClass("error", "Your Audiogram must be under " + theme.maxDuration + " seconds.");
  58. }
  59. if (!theme || !theme.width || !theme.height) {
  60. return setClass("error", "No valid theme detected.");
  61. }
  62. if (theme.labelText) {
  63. label = theme.labelText;
  64. }
  65. video.kill();
  66. audio.pause();
  67. var formData = new FormData();
  68. formData.append("audio", file);
  69. if (selection.start || selection.end) {
  70. formData.append("start", selection.start);
  71. formData.append("end", selection.end);
  72. }
  73. formData.append("theme", JSON.stringify($.extend({}, theme, { backgroundImageFile: null })));
  74. formData.append("caption", caption);
  75. formData.append("citation", citation);
  76. formData.append("label", label);
  77. setClass("loading");
  78. d3.select("#loading-message").text("Uploading audio...");
  79. $.ajax({
  80. url: "/submit/",
  81. type: "POST",
  82. data: formData,
  83. contentType: false,
  84. dataType: "json",
  85. cache: false,
  86. processData: false,
  87. success: function(data){
  88. poll(data.id, 0);
  89. },
  90. error: error
  91. });
  92. }
  93. function poll(id) {
  94. var identifier = preview.caption().replace(/\s+/g, '_').replace(/\'|\"|\.|\?|\!/g, '').toLowerCase().slice(0, 20);
  95. setTimeout(function(){
  96. $.ajax({
  97. url: "/status/" + id + "/",
  98. error: error,
  99. dataType: "json",
  100. success: function(result){
  101. if (result && result.status && result.status === "ready" && result.url) {
  102. video.update(result.url, identifier);
  103. setClass("rendered");
  104. } else if (result.status === "error") {
  105. error(result.error);
  106. } else {
  107. d3.select("#loading-message").text(statusMessage(result));
  108. poll(id);
  109. }
  110. }
  111. });
  112. }, 2500);
  113. }
  114. function error(msg) {
  115. if (msg.responseText) {
  116. msg = msg.responseText;
  117. }
  118. if (typeof msg !== "string") {
  119. msg = JSON.stringify(msg);
  120. }
  121. if (!msg) {
  122. msg = "Unknown error";
  123. }
  124. d3.select("#loading-message").text("Loading...");
  125. setClass("error", msg);
  126. }
  127. // Once images are downloaded, set up listeners
  128. function initialize(err, themesWithImages) {
  129. // Populate themes menu
  130. d3.select("#input-theme")
  131. .on("change", updateTheme)
  132. .selectAll("option")
  133. .data(themesWithImages)
  134. .enter()
  135. .append("option")
  136. .text(function(d){
  137. return d.name;
  138. });
  139. // Get initial theme
  140. d3.select("#input-theme").each(updateTheme);
  141. // Get initial caption (e.g. back button)
  142. d3.select("#input-caption").on("change keyup", updateCaption).each(updateCaption);
  143. // Get initial citation (e.g. back button)
  144. d3.select("#input-citation").on("change keyup", updateCitation).each(updateCitation);
  145. // Space bar listener for audio play/pause
  146. d3.select(document).on("keypress", function(){
  147. if (!d3.select("body").classed("rendered") && d3.event.key === " " && !d3.matcher("input, textarea, button, select").call(d3.event.target)) {
  148. audio.toggle();
  149. }
  150. });
  151. // Button listeners
  152. d3.selectAll("#play, #pause").on("click", function(){
  153. d3.event.preventDefault();
  154. audio.toggle();
  155. });
  156. d3.select("#restart").on("click", function(){
  157. d3.event.preventDefault();
  158. audio.restart();
  159. });
  160. // If there's an initial piece of audio (e.g. back button) load it
  161. d3.select("#input-audio").on("change", updateAudioFile).each(updateAudioFile);
  162. d3.select("#return").on("click", function(){
  163. d3.event.preventDefault();
  164. video.kill();
  165. setClass(null);
  166. });
  167. d3.select("#submit").on("click", submitted);
  168. }
  169. function updateAudioFile() {
  170. d3.select("#row-audio").classed("error", false);
  171. audio.pause();
  172. video.kill();
  173. // Skip if empty
  174. if (!this.files || !this.files[0]) {
  175. d3.select("#minimap").classed("hidden", true);
  176. preview.file(null);
  177. setClass(null);
  178. return true;
  179. }
  180. d3.select("#loading-message").text("Analyzing...");
  181. setClass("loading");
  182. preview.loadAudio(this.files[0], function(err){
  183. if (err) {
  184. d3.select("#row-audio").classed("error", true);
  185. setClass("error", "Error decoding audio file");
  186. } else {
  187. setClass(null);
  188. }
  189. d3.selectAll("#minimap, #submit").classed("hidden", !!err);
  190. });
  191. }
  192. function updateCaption() {
  193. preview.caption(this.value);
  194. }
  195. function updateCitation() {
  196. preview.citation(this.value);
  197. }
  198. function updateLabel() {
  199. preview.label(this.value);
  200. }
  201. function updateTheme() {
  202. var theme_obj = d3.select(this.options[this.selectedIndex]).datum(),
  203. that = this;
  204. // Automatically set the label for themes that have them
  205. preview.theme(theme_obj);
  206. if (theme_obj.labelText) {
  207. preview.label(theme_obj.labelText);
  208. $('#input-label').children().each(function (i, c) {
  209. if (c.value === that.options[that.selectedIndex].value) {
  210. $(c).prop('selected', true);
  211. return false;
  212. }
  213. });
  214. $('#input-label').prop('disabled', true);
  215. }
  216. else {
  217. $('#input-label').prop('disabled', false);
  218. }
  219. }
  220. function preloadImages(themes) {
  221. // preload images
  222. var imageQueue = d3.queue();
  223. d3.entries(themes).forEach(function(theme){
  224. if (!theme.value.name) {
  225. theme.value.name = theme.key;
  226. }
  227. if (theme.key !== "default") {
  228. imageQueue.defer(getImage, theme.value);
  229. }
  230. });
  231. imageQueue.awaitAll(initialize);
  232. function getImage(theme, cb) {
  233. if (!theme.backgroundImage) {
  234. return cb(null, theme);
  235. }
  236. theme.backgroundImageFile = new Image();
  237. theme.backgroundImageFile.onload = function(){
  238. return cb(null, theme);
  239. };
  240. theme.backgroundImageFile.onerror = function(e){
  241. console.warn(e);
  242. return cb(null, theme);
  243. };
  244. theme.backgroundImageFile.src = "/settings/backgrounds/" + theme.backgroundImage;
  245. }
  246. }
  247. function setClass(cl, msg) {
  248. d3.select("body").attr("class", cl || null);
  249. d3.select("#error").text(msg || "");
  250. }
  251. function statusMessage(result) {
  252. switch (result.status) {
  253. case "queued":
  254. return "Waiting for other jobs to finish, #" + (result.position + 1) + " in queue";
  255. case "audio-download":
  256. return "Downloading audio for processing";
  257. case "trim":
  258. return "Trimming audio";
  259. case "probing":
  260. return "Probing audio file";
  261. case "waveform":
  262. return "Analyzing waveform";
  263. case "renderer":
  264. return "Initializing renderer";
  265. case "frames":
  266. var msg = "Generating frames";
  267. if (result.numFrames) {
  268. msg += ", " + Math.round(100 * (result.framesComplete || 0) / result.numFrames) + "% complete";
  269. }
  270. return msg;
  271. case "combine":
  272. return "Combining frames with audio";
  273. case "ready":
  274. return "Cleaning up";
  275. default:
  276. return JSON.stringify(result);
  277. }
  278. }